Mysql总和的不同列如果相同的值

时间:2014-06-11 04:17:20

标签: mysql

我需要在前一列

中获得相同值的总和
 Full texts     ID  name    1       2       3       4       5       6       7       8   
            1  sai on mane  Yellow  Purple  Yellow  Purple   Red    Orange

我想获得黄色= 2的总和,紫色的总和= 2,红色的总和= 1,橙色的总和= 1; 等等... 请多多帮助谢谢

2 个答案:

答案 0 :(得分:2)

你有一个非常规范化的表结构。您应该将这些数据存储在行中, a la

ID num color
1  1   Yellow
1  2   Purple
1  3   Yellow
1  4   Purple
1  5   Red
1  6   Orange

但是,假设你被迫使用这个...首先我会压扁你的桌子:

select `1` as color from myTable
union all 
select `2` as color from myTable
union all 
select `3` as color from myTable
union all 
select `4` as color from myTable
union all 
select `5` as color from myTable
union all 
select `6` as color from myTable
union all 
select `7` as color from myTable
union all 
select `8` as color from myTable

然后您可以轻松地从此查询聚合:

select color, count(1)
from (
    select `1` as color from myTable
    union all 
    select `2` as color from myTable
    union all 
    select `3` as color from myTable
    union all 
    select `4` as color from myTable
    union all 
    select `5` as color from myTable
    union all 
    select `6` as color from myTable
    union all 
    select `7` as color from myTable
    union all 
    select `8` as color from myTable
) x

答案 1 :(得分:-2)

试试这个,

select colorName, count(colorName) from tableName group by colorName;