基于COUNT的组合行并创建多个列

时间:2017-09-21 21:54:59

标签: sql-server-2012

如何将多行汇总到具有多个列的单行,如表B?

Table A

 Partyid Origin
 1       Atm
 1       Auto
 1       Mobile
 1       mobile

Table B

Partyid               COUNT (atm)   COUNT (auto)    COUNT (mobile)
 1                       1                1                2

我使用了这个查询:

SELECT partyid, 
CASE WHEN origin = 'atm'   THEN COUNT (origin) ELSE '0' END AS N_ATM,
CASE WHEN origin = 'auto'  THEN COUNT (origin) ELSE '0' END AS N_auto,
CASE WHEN origin = 'mobile' THEN COUNT (origin) ELSE '0' END AS N_Mobile,

FROM XXX
GROUP BY partyid

并带来了这个结果:

Partyid COUNT (atm) COUNT (auto)    COUNT (mobile)

1            1          0               0
1            0          1               0
1            0          0               2

1 个答案:

答案 0 :(得分:1)

请勿使用COUNT() - 请改用SUM(),如下所示:

SELECT partyid, 
    SUM(CASE 
        WHEN origin = 'atm' THEN 1 ELSE 0 
        END) AS N_ATM,
    SUM(CASE 
        WHEN origin = 'auto' THEN 1 ELSE 0 
        END) AS N_auto,
    SUM(CASE 
        WHEN origin = 'mobile' THEN 1 ELSE 0 
        END) AS N_Mobile
FROM XXX
GROUP BY partyid