I have a problem on how to fetch the number of occurrences of a value in between two columns in MySQL.
id1 col1 col2
2 5 3
3 3 4
4 2 1
5 1 3
6 null 2
How am I able to get the number of occurences between the two columns like the following?
value occurrence
3 3
1 2
2 2
4 1
5 1
You could union all
the columns and then apply a count
aggregate function:
SELECT val, COUNT(*) AS occurrence
FROM (SELECT col1 AS val
FROM mytable
UNION ALL
SELECT col2 AS val
FROM mytable) x
GROUP BY val
ORDER BY occurrence DESC
Depending on the actual data (number of rows per value) pre-aggregating might be more efficient, simply try it out:
SELECT val, SUM(occurrence) AS occurrence
FROM (SELECT col1 AS val, COUNT(*) AS occurrence
FROM mytable
UNION ALL
SELECT col2 AS val, COUNT(*) AS occurrence
FROM mytable) x
GROUP BY val
ORDER BY occurrence DESC
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.