我有一个包含以下数据的表(staffs_table);
name profession
------------------------------
Corbin Human Resources|Accountant
Cort Programmer|Receptionist|Helpdesk
我希望每个职业count个人数,以便使我的结果如下;
profession number_of_staffs
---------------------------------------
Human Resources 1
Accountant 1
Programmer 1
Receptionist 1
Helpdesk 1
我尝试了以下SQL查询,但没有成功;
SELECT profession, COUNT(*) AS number_of_staffs FROM staffs_table GROUP BY profession ORDER BY COUNT(*) DESC;
输出:
profession number_of_staffs
---------------------------------------------
Human Resources|Accountant 1
Programmer|Receptionist|Helpdesk 1
也尝试了以下;
SELECT staffs_table.name,
SUBSTRING_INDEX(SUBSTRING_INDEX(staffs_table.profession, '|', numbers.n), '|', -1) profession
FROM
numbers INNER JOIN staffs_table
ON CHAR_LENGTH(staffs_table.profession)
-CHAR_LENGTH(REPLACE(staffs_table.profession, '|', ''))>=numbers.n-1
输出:
name profession
------------------------------
Corbin Human Resources
Corbin Accountant
Cort Programmer
Cort Receptionist
Cort Helpdesk
提前感谢!
SELECT jsontable.profession, COUNT(jsontable.profession) number_of_staffs
FROM staffs_table
CROSS JOIN JSON_TABLE( CONCAT('["', REPLACE(staffs_table.profession, '|', '","'), '"]'),
"$[*]" COLUMNS( profession VARCHAR(254) PATH "$" )
) AS jsontable
GROUP BY jsontable.profession;
fiddle