SQL Server:多行值到一行



我有一个方案,其中基于状态和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,但我无法使其正常工作。

请建议..

因为您正在调整状态,因此我建议它不应出现在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

相关内容

  • 没有找到相关文章

最新更新