我想按类别显示db中的记录并计算状态
假设我在数据库中有这些记录,
agent_tbl
=========================
| directors || status |
=========================
| AAA || Suspended |
| BBB || Deleted |
| CCC || Active |
| AAA || Deleted |
这是我想要获得的结果:
Directors | Active | Suspended | Deleted |
------------------------------------------
AAA | 0 | 1 | 1 |
------------------------------------------
BBB | 0 | 0 | 1 |
------------------------------------------
CCC | 1 | 0 | 0 |
------------------------------------------
Total 1 1 2 |
------------------------------------------
这是我的查询
SELECT director,COUNT(*)
FROM agent_tbl
GROUP BY director;
答案 0 :(得分:0)
SELECT Directors,
SUM(status = 'Active') AS Active,
SUM(status = 'Suspended') AS Suspended,
SUM(status = 'Deleted') AS Deleted
FROM agent_tbl
GROUP BY Directors
答案 1 :(得分:0)
--For each director
select directors,
count(case when status = 'Active' then 1 else null end) as 'Active',
count(case when status = 'Suspended' then 1 else null end) as 'Suspended',
count(case when status = 'Deleted' then 1 else null end) as 'Deleted'
from agent_tbl
group by directors
union
--Hard code for the total row
select 'Total',
count(case when status = 'Active' then 1 else null end) as 'Active',
count(case when status = 'Suspended' then 1 else null end) as 'Suspended',
count(case when status = 'Deleted' then 1 else null end) as 'Deleted'
from agent_tbl
演示here。