我有一个场景,在基于status和id的SQL Server数据库中,我必须对行进行分组并显示计数。我正在尝试,但我在单独的单独行中获取值,如下所示
select
req_id as bid, status,
(case when status = 1 then 1 else 0 end) as accept,
count(case when status = 2 then 1 else 0 end) as rejected,
(case when status = 3 then 1 else 0 end) as noResp
from
temp_allo
group by
req_id, status
结果是
bid status accept rejected noResp
--------------------------------------
1 1 1 1 0
2 1 1 1 0
3 1 1 1 0
2 2 0 2 0
3 2 0 1 0
(状态仅供参考)
但我需要这样的结果:
bid accept rejected noResp
-----------------------------------
1 1 0 0
2 1 2 0
3 1 1 0
我从stackoverflow获得了很多样本,我尝试了MAX()
,SUM()
,CASE
,但我无法使其正常工作。
请建议..
答案 0 :(得分:3)
因为您正在转变状态,因此我建议它不应出现在GROUP BY
列表中。而是聚合在req_id
上,然后将MAX()
与您当前的CASE
表达式一起使用。
select
req_id as bid,
max(case when status = 1 then 1 else 0 end) as accept,
max(case when status = 2 then 1 else 0 end) as rejected,
max(case when status = 3 then 1 else 0 end) as noResp
from temp_allo
group by req_id