MySQL Group By在多列上相等的值

时间:2014-11-08 08:43:36

标签: mysql sql

从示例开始:

对于这些数据:

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

问题解释如下:

如果列共享公共值,那么查询中返回的行如何在多列上压缩?在此示例中,如何将Col1Col2Col3分组到同一个ColValue结果中?

1 个答案:

答案 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;