sql查找值小于某个值

时间:2017-02-09 22:41:21

标签: mysql

我有3张桌子 现在,我需要找到每个季度,少于5名学生(但至少有一名学生)的课程数量。 我拥有的是

student (sid);
course (cid);
record (sid, cid, qtr, year, grade);

insert into record values ('A_001', 'CSE105', 'F', 2015, 3);
insert into record values ('A_001', 'CSE132A', 'F', 2015, 4);

insert into record values ('A_001', 'CSE132B', 'F', 2016, 1);
insert into record values ('A_002', 'CSE132B', 'F', 2016, 4);
insert into record values ('A_003', 'CSE132B', 'F', 2016, 2);
insert into record values ('A_004', 'CSE132A', 'F', 2016, 2);
insert into record values ('A_005', 'CSE132A', 'F', 2016, 3);
insert into record values ('A_002', 'CSE107', 'F', 2016, 4);
insert into record values ('A_003', 'CSE107', 'F', 2016, 4);
insert into record values ('A_005', 'CSE107', 'F', 2016, 2);



insert into record values ('A_002', 'CSE105', 'W', 2017, 4);
insert into record values ('A_003', 'CSE105', 'W', 2017, 3);
insert into record values ('A_004', 'CSE105', 'W', 2017, 3);
insert into record values ('A_005', 'CSE105', 'W', 2017, 2);
insert into record values ('A_006', 'CSE105', 'W', 2017, 1);
insert into record values ('A_004', 'CSE132B', 'W', 2017, 4);
insert into record values ('A_005', 'CSE132B', 'W', 2017, 2);

我想看的结果

qtr year num
 F  2015  2
 F  2016  3
 W  2017  1

但我得到的是显示宿舍的课程数量少于5.我想我只需要计算每个季度,同一课程显示不到5次,有没有人知道怎么做,非常感谢你

1 个答案:

答案 0 :(得分:1)

只需将class_id添加到查询中即可。

select r.cid, r.qtr,r.year,count(*) as num
from record r
group by r.cid, r.qtr,r.year
having num <5

如果您只想要类的计数,而不是所有的ID,请将它放入子查询并计算它们:

SELECT qtr, year, COUNT(*)
FROM (
    select r.cid, r.qtr,r.year,count(*) as num
    from record r
    group by r.cid, r.qtr,r.year
    having num <5
) AS subquery
GROUP BY qtr, year

DEMO