我需要计算在2个mysql列中找到结果的次数。
实施例
| Column A | Column B |
| white | black |
| black | green |
| orange | white |
| black | blue |
我需要得到这个结果:
white -> 2 times
black -> 3 times
green -> 1 time
orange -> 1 time
blue -> 1 time
我为单列做了它,它起作用了:
SELECT
column_name
, COUNT(column_name) as total
FROM table_name
WHERE (......)
GROUP BY column_name
HAVING column_name != ''
ORDER BY total DESC
我无法理解它如何适用于2列
答案 0 :(得分:2)
对于您的特定用途,我会做这样的事情:
SELECT col, COUNT(col) FROM
(SELECT columnA as col FROM table
UNION ALL SELECT columnB FROM table) as tmp_table
WHERE ... GROUP BY ... HAVING ... ORDER BY ...
答案 1 :(得分:2)
尝试使用UNION ALL
子句,在内部查询中选择所需的所有内容(意味着,在嵌套查询中保留WHERE
子句)
SELECT
column_nameA
,count(*) AS total
FROM(
SELECT
column_nameA
FROM table_name
WHERE (......)
UNION ALL
SELECT
column_nameb
FROM table_name
WHERE (......)
)a
GROUP BY column_nameA
HAVING column_name != ''
ORDER BY 1