I need to count how many times a result is found in 2 mysql column.
Ex.
| Column A | Column B |
| white | black |
| black | green |
| orange | white |
| black | blue |
I need to get this result:
white -> 2 times
black -> 3 times
green -> 1 time
orange -> 1 time
blue -> 1 time
I did it for single column and it works:
SELECT
column_name
, COUNT(column_name) as total
FROM table_name
WHERE (......)
GROUP BY column_name
HAVING column_name != ''
ORDER BY total DESC
I can't understand how it can works with 2 columns
For your particular use, I would do something like this:
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 ...
Try it with a UNION ALL
clause, selecting all which you need in the inner query (meaning, keep the WHERE
clause in the nested query)
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.