我有一个名为'services'的MySql表,其结构为:机构,角色
Institution | Role
Human Ressource | Responsable
Human Ressource | Responsable
Human Ressource | Agent
Human Ressource | Agent
Human Ressource | Chief
IT Service | Responsable
IT Service | Agent
Client Relate | Responsable
Client Relate | Chief
Control Mgm | Responsable
Control Mgm | Agent
Control Mgm | Agent
和一个查询以计算每个机构的角色数量,例如:
SELECT a.institution, Responsable, Agent, Chief
FROM
(
SELECT a.institution
FROM services a
WHERE a.month = '2019-04'
GROUP BY a.institution
) a,
(
SELECT b.institution, NULLIF(count(b.role) ,0) AS Responsable
FROM services b
WHERE
b.month = '2019-04' AND
b.role = 'Responsable'
GROUP BY b.institution
) b,
(
SELECT c.institution, NULLIF(count(c.role), 0) AS Agent
FROM services c
WHERE
c.month = '2019-04' AND
c.role = 'Agent'
GROUP BY c.institution
) c,
(
SELECT d.institution, NULLIF(count(d.role), 0) AS Chief
FROM services d
WHERE
d.month = '2019-04' AND
d.role = 'Chief'
GROUP BY d.institution
) d
WHERE
a.institution = b.institution AND
a.institution = d.institution
GROUP BY 1
ORDER BY a.institution ASC
我想在一个sql语句中达到的结果是:
Institution | Responsable | Agent | Chief
Human Ressource | 2 | 2 | 1
IT Service | 1 | 1 | 0
Client Relate | 1 | 0 | 1
Control Mgm | 1 | 2 | 0
但是我得到一个非常奇怪的结果集
institution | Responsable | Agent | Chief
Client Relate | 1 | 2 | 1
Human Ressource | 2 | 2 | 1
我在这里创建了sqlfiddle
任何想法都会受到高度赞赏。 Tnx
答案 0 :(得分:2)
使用条件聚合
SELECT a.institution,
coalesce(count(case when role = 'Responsable' then 1 end),0) AS Responsable,
coalesce(count(case when role = 'Agent' then 1 end),0) AS Agent,
coalesce(count(case when role = 'Chief' then 1 end),0) AS Chief
FROM services a
WHERE a.month = '2019-04'
GROUP By a.institution
答案 1 :(得分:2)
您可以使用CASE
语句,然后汇总结果来使用它:
SELECT institution,
SUM(Responsable) AS Responsable,
SUM(Agent) AS Agent,
SUM(Chief) AS Chief
FROM (
SELECT institution,
CASE
WHEN role = 'Responsable' THEN 1
ELSE 0
END AS Responsable,
CASE
WHEN role = 'Agent' THEN 1
ELSE 0
END AS Agent,
CASE
WHEN role = 'Chief' THEN 1
ELSE 0
END AS Chief
FROM services
WHERE `month` = '2019-04'
) a
GROUP BY institution
ORDER BY institution ASC;
这将创建一个结果集,该结果集的每一行的相应列中的数字为1,然后根据该机构将每一行的计数按institution
和SUM
分组。 / p>
结果:
Client Relate 1 0 1
Control Mgm 1 2 0
Human Ressource 2 2 1
IT Service 1 1 0
显示此内容的SQL Fiddle。
答案 2 :(得分:1)
感谢您提供表格架构,示例数据和所需的输出。
试试这个。
SELECT institution,
Sum(CASE WHEN role = 'Responsable' THEN 1 ELSE 0 end) AS Responsable,
Sum(CASE WHEN role = 'Agent' THEN 1 ELSE 0 end) AS Agent,
Sum(CASE WHEN role = 'Chief' THEN 1 ELSE 0 end) AS Chief
FROM services
GROUP BY institution
如果需要,还可以添加where子句。
示例:WHERE month = '2019-04'
输出
+------------------+--------------+--------+-------+
| institution | Responsable | Agent | Chief |
+------------------+--------------+--------+-------+
| Client Relate | 1 | 0 | 1 |
| Control Mgm | 1 | 2 | 0 |
| Human Ressource | 2 | 2 | 1 |
| IT Service | 1 | 1 | 0 |
+------------------+--------------+--------+-------+