繁体   English   中英

SQL-如何获取具有相同类别的几列的汇总计数

[英]SQL - How to get aggregate counts across several columns with the same categories

我有一个表,其中有多个列具有相同的类别集。 我想获取类别在每一列中出现的次数的总计数。 有没有一种方法可以通过单个select语句来实现?

这是我的起始数据集:

C1  C2  C3
A   ?   A
A   ?   ?
B   ?   A
B   ?   ?
?   B   B

我想按列C1,C2和C3按组A和B进行计数。 结果应如下所示:

Group   C1  C2  C3
A       2   0   2
B       2   1   1

我目前正在使用以下方法完成此操作:

Select 
'A' as Group, Count(case when C1 = 'A' then 1 else NULL) as C1...
UNION
Select 
'B' as Group, Count(case when C1 = 'B' then 1 else NULL) as C1...

这是您的结构略有变化:

select g.grp, 
       sum(case when t.C1 = g.grp then 1 else 0 end) as C1,
       sum(case when t.C2 = g.grp then 1 else 0 end) as C2,
       sum(case when t.C3 = g.grp then 1 else 0 end) as C3
from (select 'A' as grp union all select 'B') g cross join
     t
group by g.grp;

确切的语法可能因数据库而异。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM