Mysql 具有max(count())的sql返回零行
我正试图获得课程表重叠的教室,我的桌子:课程:Mysql 具有max(count())的sql返回零行,mysql,sql,count,max,having,Mysql,Sql,Count,Max,Having,我正试图获得课程表重叠的教室,我的桌子:课程: COURSE_ID NAME 11 matematika 22 logika 33 himiya 44 sport 55 algoritmika 66 hedva 77 algebra linearit 附表: ID COURSE_ID ID_ROOM DAY HOUR 1 11
COURSE_ID NAME
11 matematika
22 logika
33 himiya
44 sport
55 algoritmika
66 hedva
77 algebra linearit
附表:
ID COURSE_ID ID_ROOM DAY HOUR
1 11 105 Mon 10am
2 11 105 Wen 10am
3 11 105 Thu 10am
4 22 105 Mon 10am
5 22 205 Wen 10am
6 22 105 Thu 10am
7 33 305 Mon 11am
8 33 105 Mon 10am
教室:
ID_ROOM LOCATION CAPACITY
105 A 20
205 B 10
305 C 30
我的sql是:
select class_room.ID_ROOM as crid, class_room.LOCATION, schedule.DAY as d, schedule.HOUR as h, count(courses.COURSE_ID) as count
from schedule
natural join class_room
natural join courses
group by crid, d, h
order by count desc;
我得到:
crid LOCATION d h count
105 A Mon 10am 3
105 A Thu 10am 2
305 C Mon 11am 1
105 A Wen 10am 1
205 B Wen 10am 1
但我只需要显示count的所有最大值(目前为1行)。
我试着
但返回的是空表。
怎么了?或者,可能是另一种解决方案的建议,以获得我需要的?这将返回计数最高的所有行:
select ID_ROOM as crid, DAY as d, HOUR as h,
count(*) as cnt
from schedule
group by crid, d, h
having
count(*)
= ( select count(*) as cnt
from schedule
group by ID_ROOM, DAY, HOUR
order by cnt desc
limit 1
)
现在将其加入
教室
以获取位置
以下内容将返回与最大计数匹配的所有组
您能给出一个用于测试的示例数据集吗?例如,在SQL FIDLE中。我使用replace
max(count)
添加了所有测试数据,并使用count(courses.COURSE\u ID)=1
。这将返回count=1的行,可能我的问题不清楚,但我需要显示count的最大值!我的意思是,重叠课程是指计数大于1的课程。你能发布你的预期输出吗,我还不清楚。
select ID_ROOM as crid, DAY as d, HOUR as h,
count(*) as cnt
from schedule
group by crid, d, h
having
count(*)
= ( select count(*) as cnt
from schedule
group by ID_ROOM, DAY, HOUR
order by cnt desc
limit 1
)
select class_room.ID_ROOM as crid
, class_room.LOCATION
, schedule.DAY as d
, schedule.HOUR as h
, count(courses.COURSE_ID) as count
from schedule
natural join class_room
natural join courses
group by
crid, d, h
having count(*) = (
select max(count)
from (
select count(courses.COURSE_ID) as count
from schedule
natural join class_room
natural join courses
group by
id_room, day, hour
) maxcount
)