[英]Complex SQL Select query with inner join
我的SQL查询需要在日期旁边返回一个值列表,但是据我所知,我只能做到这一点。
这是我的SQL:
select lsu_students.student_grouping,lsu_attendance.class_date,
count(lsu_attendance.attendance_status) AS count
from lsu_attendance
inner join lsu_students
ON lsu_students.student_grouping="Central1A"
and lsu_students.student_id=lsu_attendance.student_id
where lsu_attendance.attendance_status="Present"
and lsu_attendance.class_date="2015-02-09";
返回:
student_grouping class_date count
Central1A 2015-02-09 23
我希望它返回:
student_grouping class_date count
Central1A 2015-02-09 23
Central1A 2015-02-10 11
Central1A 2015-02-11 21
Central1A 2015-02-12 25
该查询根据学生分组获取日期列表:
select distinct(class_date)from lsu_attendance,lsu_students
where lsu_students.student_grouping like "Central1A"
and lsu_students.student_id = lsu_attendance.student_id
order by class_date
我认为您只需要一个group by
:
select s.student_grouping, a.class_date, count(a.attendance_status) AS count
from lsu_attendance a inner join
lsu_students s
ON s.student_grouping = 'Central1A' and
s.student_id = a.student_id
where a.attendance_status = 'Present'
group by s.student_grouping, a.class_date;
评论:
where
。 group by
。 除MySQL外,任何其他SQL引擎都将要求此功能。 只需取出and lsu_attendance.class_date="2015-02-09"
或将其更改为一个范围,然后添加(最后) GROUP BY lsu_students.student_grouping,lsu_attendance.class_date
。
您要寻找group by子句,以限制聚合(例如count函数)在每个组中工作。
要获取每个日期每个小组中的学生人数,您可以执行以下操作:
select student_grouping, class_date, count(*) as present_count
from lsu_students join lsu_attendance using (student_id)
where attendance_status = 'Present'
group by student_grouping, class_date
注意:在您的示例中, 使用比on简单(如果您的SQL支持),并且如果列名没有出现在一个以上的表中,则不必将表名放在每个字段名之前(尽管它不会)受伤)。
如果要限制包括哪些数据行,请将约束条件放入where子句中(这将限制要计数的行)。 如果要限制显示的聚合值,则必须使用Haveing子句。 例如,要查看每天出现的Central1A学生人数,但仅显示出现了20多名学生的日期:
select student_grouping, class_date, count(*) as present_count
from lsu_students join lsu_attendance using (student_id)
where attendance_status = 'Present' and student_grouping = 'Central1A'
group by student_grouping, class_date
having count(*) > 20
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.