mysql group by value in multiple columns

时间:2015-02-10 12:52:33

标签: mysql sql group-by

    code1 | code2 | code3 | code4 | code5
row1    A       B       C
row2    B       A       D        E
row3   F       C 

如何将此表与codeX列中的值计数组合在一起 所以

A: 2
   B: 2
   C: 2
   D: 1
   E: 1
   F: 1

2 个答案:

答案 0 :(得分:1)

如果我理解正确,您需要列出某些内容的列表。您可以使用group_concat

对表格进行取消操作
select code, count(*) as cnt, group_concat(which)
from (select code1 as code, 'code1' as which from table union all
      select code2, 'code2' as which from table union all
      select code3, 'code3' as which from table union all
      select code4, 'code4' as which from table
     ) c
where code is not null
group by code;

我使用完整列名而不是#1 - 它似乎更有用。但您可以为#1添加which等。

答案 1 :(得分:0)

SELECT productCode, count(*) AS count
FROM
(
    SELECT Code1 AS productCode FROM table
    UNION ALL
    SELECT Code2 FROM table
     UNION ALL
    SELECT Code3 FROM table
     UNION ALL
    SELECT Code4 FROM table
     UNION ALL
    SELECT Code5 FROM table

) AS codes
GROUP BY productCode
ORDER BY count DESC