对于这些数据:
NAME Col1 Col2 Col3
row1 0 2 4
row2 1 5 0
row3 1 1 0
所需的查询输出是:
ColValue CountInCol1 CountInCol2 CountInCol3
0 1 0 2
1 2 1 0
2 0 1 0
4 0 0 1
5 0 1 0
如果列共享公共值,那么查询中返回的行如何在多列上压缩?在此示例中,如何将Col1
,Col2
和Col3
分组到同一个ColValue
结果中?
答案 0 :(得分:1)
我会通过取消数据然后重新编译来完成此操作:
select colvalue,
sum(which = 'col1') as CountInCol1,
sum(which = 'col2') as CountInCol2,
sum(which = 'col3') as CountInCol3
from (select 'col1' as which, col1 as colvalue from data union all
select 'col2', col2 from data union all
select 'col3', col3 from data
) d
group by colvalue;