所以我想说我有
| id | value |
--------------
| 1 | A |
| 2 | B |
| 3 | B |
| 4 | A |
| 5 | A |
然后运行以下SQL语句
SELECT value, COUNT(*) AS `num` FROM test2 GROUP BY value
我会得到A:3和B:2
很好,但是如果我想从多个列组合
| id | value | Value2 | Value 3|
---------------------------------
| 1 | A | A | A |
| 2 | B | A | B |
| 3 | B | B | B |
| 4 | A | A | A |
| 5 | A | B | A |
在上面A:9 B:6。目前我可以运行上述3次,然后在php端添加值。但我认为可能有一个巧妙的小技巧可以在1个声明中完成所有工作。
答案 0 :(得分:1)
使用Union all
将三列合并为单列,然后在外部查询中查找每个组的计数。试试这个。
SELECT value,
Count(value)
FROM (SELECT value AS value FROM test2
UNION ALL
SELECT value2 FROM test2
UNION ALL
SELECT value3 FROM test2)a
GROUP BY value
答案 1 :(得分:1)
首先,您可以为每个单独的列和组添加COUNT
个值,然后将结果与UNION ALL
和最后SUM
组合用于每个组。
SELECT `num`, SUM(`num`)
FROM (
SELECT value, COUNT(*) AS `num` FROM test2 GROUP BY value
UNION ALL
SELECT value2, COUNT(*) AS `num` FROM test2 GROUP BY value2
UNION ALL
SELECT value3, COUNT(*) AS `num` FROM test2 GROUP BY value3
) GROUP BY `num`