我有一个包含多个列的表,这些列具有相同的类别集。我希望获得类别在每列中显示的次数的总计数。有没有办法用一个select语句来完成这个?
这是我的起始数据集:
C1 C2 C3
A ? A
A ? ?
B ? A
B ? ?
? B B
我想得到A组和A组的评分。列C1,C2和C3为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...
答案 0 :(得分:2)
这是您的结构的一个小变化:
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;
确切的语法可能因数据库而异。