2015-02-10 104 views
0
code1 | code2 | code3 | code4 | code5 
row1 A  B  C 
row2 B  A  D  E 
row3 F  C 

我怎麼能組此表的價值數法典列 所以mysql的GROUP BY值

A: 2 
    B: 2 
    C: 2 
    D: 1 
    E: 1 
    F: 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 
1

如果我理解正確的話,你想要的列的列表,其中一些出現。您可以UNPIVOT表的使用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等。

+0

嗯,我想與codeX內的值組合,所以不僅僅是爲了某些東西。我想在codeX – tugce 2015-02-10 13:02:50

+0

中實現所有值的結果,我只需要計數外觀,任何想法? – tugce 2015-02-10 13:14:35

+0

@tugce。 。 。只需使用'count(*)'。 – 2015-02-10 13:19:11