简体   繁体   中英

Find the row with Maximum Count

I need to find the row with maximum count. There's only one table, so it should be easy, but it isn't. Below is the content of table:

+------+------+------+
| row1 | row2 | row3 |
+------+------+------+
|    3 |    2 |    1 |
|    6 |    4 |    5 |
|    6 |    2 |    1 |
+------+------+------+

I need to find maximum count item for row1: Using: SELECT COUNT(*) AS c, row1 AS name FROM draw GROUP BY name; Give me the result:

+------+------+
|   c  | name |
+------+------+
|    1 |    3 |
|    2 |    6 |
+------+------+

But I want to display only one row with the maximum "c":

+------+------+
|   c  | name |
+------+------+
|    2 |    6 |
+------+------+

Using: SELECT MAX(c), name ( SELECT COUNT(*) AS c, row1 AS name FROM draw GROUP BY name ) AS counts;

Give me result:

+------+------+
|   c  | name |
+------+------+
|    2 |    3 |
+------+------+

It means that it gives maximum count (c), but give first number in name row.

Is there way to fix it?

I think this is what you want, but your requirements are a little unclear. If this was any other platform you could use windowing functions would would be better.

SELECT *
FROM (
  SELECT COUNT(*) AS c, row1
  FROM draw 
  GROUP BY row1
) as Sub1
WHERE Sub.c = (
  SELECT Max(c) 
  FROM (
    SELECT COUNT(*) AS c
    FROM draw 
    GROUP BY row1
  ) as Sub2
) as Sub3
select top 1 row1, count(*)
from draw
group by row1
order by count(*) desc

Order by the count descending (ie highest count first) and take the first one only.

You can try this

SELECT COUNT(  `row1` ) AS c,  `row1` 
FROM  `draw` 
GROUP BY  `row1` 
ORDER BY  `row1` DESC 
LIMIT 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM