Select all rows with the same aggregated value

时间:2018-03-25 20:51:09

标签: mysql sql

There is a task: develop a fragment of the Web site that provides work with one table.

Attributes of the table:

Day of the week, 
Time of the beginning of the lesson, 
Subject name, 
Number of the audience, 
Full name of the teacher. 

We need to make a query: determine the day of the week with the largest number of entries, if there are more than one maximum (ie, they are the same), then output them all. I did the query as follows:

SELECT COUNT (*) cnt, day 
FROM schedule 
GROUP BY day 
ORDER BY cnt DESC 
LIMIT 1; 

But if there are several identical maxima, then only one is displayed. How to write a query which returns them all?

1 个答案:

答案 0 :(得分:2)

You can use your query as a subquery in the HAVING clause, e.g.:

SELECT day, count(*) as cnt
FROM schedule
GROUP BY day
HAVING count(*) = (
    SELECT count(*) as cnt
    FROM schedule 
    GROUP BY day
    ORDER BY cnt DESC
    LIMIT 1
    )
ORDER BY day