MySQL将多个GROUP BY列放入一列

时间:2014-01-21 04:49:39

标签: mysql

我在Mysql中查询了Group By

看起来像我的桌子 col1和col2

1 1
   4 6
   5 4
   2 3
   1 9
   2 1
   3 2

需要像这样显示输出

col1& col2和count(col1& col2)

1   4
2   3
3   2
4   2
5   1
6   1
9   1

任何人都建议使用mysql查询将上述结果作为输出?

提前致谢

3 个答案:

答案 0 :(得分:2)

SELECT some_table.col, count(some_table.col)
FROM 
(
SELECT col1 as col FROM table
UNION ALL
SELECT col2 as col FROM table
)  AS some_table
GROUP BY col

这样的事情 - MySQL COUNT() multiple columns

答案 1 :(得分:2)

SELECT my_table.col, count(my_table.col)
FROM 
(
   SELECT col1 as col FROM your_table
   UNION ALL
   SELECT col2 as col FROM your_table
) AS my_table
GROUP BY col

不要忘记表名,你必须有一个表别名。我试图将此作为评论,但没有足够的评论意见。只是@tigran的附录

答案 2 :(得分:0)

最后,在大家的帮助下,我得到了解决方案

SELECT col,count(col)FROM(     SELECT col1 as col FROM table_name     UNION ALL     SELECT col2 as col FROM table_name )AS temp_table GROUP BY col ORDER BY col

感谢大家@ Marc B,@ Tigran,@ sepfalcon和@Gilberg