SQL Server:将多行值转换为单行

时间:2017-05-06 09:45:03

标签: sql sql-server aggregate-functions

我有一个场景,在基于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,但我无法使其正常工作。

请建议..

1 个答案:

答案 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