0

here is my table Table1:

examplecolumn1 | examplecolumn2
--------------------------------
AAA            | 555
BBB            | 555
AAA            | 333
AAA            | 444
CCC            | 111

I'm trying to make a query that returns

AAA 3, 555 2

the most frequent value in column1 and the frequency, and the same for the column 2.
can I do it with a single query in PHP? or should I do more than one query? I have to do it for 4 columns, so if I do it in just one query is better, but I have no idea

I tried:

SELECT COUNT(`examplecolumn1`) AS FREQ FROM `Table1` GROUP BY `examplecolumn1`

thanks in advance

1 Answers1

0

To get the most frequent value in a particular column, do:

SELECT examplecolumn1, COUNT(*) AS count
FROM Table1
GROUP BY examplecolumn1
ORDER BY count DESC
LIMIT 1

If you want this for multiple columns in a single query, just combine them with UNION:

SELECT examplecolumn1, COUNT(*) AS count
FROM Table1
GROUP BY examplecolumn1
ORDER BY count DESC
LIMIT 1
UNION
SELECT examplecolumn2, COUNT(*) AS count
FROM Table1
GROUP BY examplecolumn2
ORDER BY count DESC
LIMIT 1
Barmar
  • 741,623
  • 53
  • 500
  • 612