如何使用多列不同的计数?

时间:2016-04-14 03:39:23

标签: sql

输入:

id sem1 sem2 sem3 sem4 sem5 sem6 sem7
1    S   O     S    R  null null null
2    O   O     R    R    S  null null

期望的输出:

id O   R   S
1  1   1   2
2  2   2   1

1 个答案:

答案 0 :(得分:2)

如果您的数据库支持APPLY/UNPIVOT运算符,请使用此

CROSS APPLY方法

SELECT id, 
       SUM(CASE WHEN val = 'O' THEN 1 ELSE 0 END) O, 
       SUM(CASE WHEN val = 'R' THEN 1 ELSE 0 END) R, 
       SUM(CASE WHEN val = 'S' THEN 1 ELSE 0 END) S 
FROM   mytable 
       CROSS apply (VALUES (sem1), 
                           (sem2), 
                           (sem3), 
                           (sem4), 
                           (sem5), 
                           (sem6), 
                           (sem7)) cs(val) 
GROUP  BY id 

UNPIVOT方法

SELECT id, 
       SUM(CASE WHEN val = 'O' THEN 1 ELSE 0 END) O, 
       SUM(CASE WHEN val = 'R' THEN 1 ELSE 0 END) R, 
       SUM(CASE WHEN val = 'S' THEN 1 ELSE 0 END) S 
FROM   (SELECT * 
        FROM   mytable) a 
       UNPIVOT (val 
               FOR col IN ( sem1, 
                            sem2, 
                            sem3, 
                            sem4, 
                            sem5, 
                            sem6, 
                            sem7 )) upv 
GROUP  BY id 

我个人更喜欢CROSS APPLY方法而不是UNPIVOT,因为它更具可读性。性能方面两者都是相同的