mysql 在多列中按值分组

mysql group by value in multiple columns

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

如何将此 table 与 codeX 列中的值计数分组 所以

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

如果我没理解错的话,您需要的是出现某些内容的列的列表。您可以反转 table 并使用 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——它似乎更有用。但是你可以为 which.

输入 #1
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