I was just wondering what MySQL code could I use to find the most common value across a series of columns containing similar values.
SELECT `column`,
COUNT(`column`) AS `value_occurrence`
FROM `my_table`
GROUP BY `column`
ORDER BY `value_occurrence` DESC
LIMIT 1;
I know I can use the above code to the find most common value in a single column but how would I expand this to find the value in 3 columns?
Eg
Column 1: 1, 2, 2, 4
Column 2: 1, 3, 2, 1
Column 3: 1, 2, 2, 2
Result : 2
2
Answers
Use
UNION
to move all the columns into a single column.All you have to do is replace
column
inCOUNT(column)
with an asterisk (*). That is the universal selector for accessing all records of a table. Then in yourORDER BY
clause, specifyallColumns
as the scope of the data you want to order it by.