我有代码可以提供出席'我们学校日期表的日期(取消假期,周末,工作日等)。
AttendanceDate
8/30/2017
8/31/2017
9/1/2017
9/5/2017
9/6/2017
9/7/2017
9/8/2017
9/11/2017
9/12/2017
9/13/2017
9/14/2017
9/15/2017
9/18/2017
9/19/2017
9/20/2017
9/21/2017
9/22/2017
9/25/2017
9/26/2017
9/27/2017
9/28/2017
9/29/2017
10/2/2017
10/3/2017
我有一些代码可以构建一个临时表,为我提供一个学生ID列表以及他们缺席的日期。
studentID | currDate
89 | 9/18/2017
89 | 10/5/2017
89 | 10/16/2017
537 | 9/6/2017
541 | 9/11/2017
541 | 9/27/2017
549 | 9/18/2017
549 | 9/20/2017
549 | 9/28/2017
549 | 9/29/2017
549 | 10/2/2017
549 | 10/3/2017
549 | 10/4/2017
549 | 10/5/2017
549 | 10/10/2017
550 | 10/19/2017
845 | 9/26/2017
845 | 10/2/2017
897 | 10/5/2017
897 | 10/20/2017
990 | 9/22/2017
990 | 9/26/2017
990 | 9/27/2017
990 | 9/28/2017
990 | 10/3/2017
我想要做的是为每个学生ID将他们缺席的日期与上学日考勤日期进行比较,并找出累计缺勤。我一直绞尽脑汁试图看看如何做到这一点(温度表,光标等),但是我们还没能弄明白。
我通过AquaData Studio使用MySQL 2012。有任何想法吗?最后,一份报告给了我一份累计缺席超过5人的学生名单,这是我所追求的。谢谢!
答案 0 :(得分:0)
这可能就是你想要的:
MySQL 5.6架构设置:
查询1 :
SELECT studentID
FROM absent
WHERE currDate IN (
SELECT AttendanceDate
FROM school_days
)
GROUP BY studentID
HAVING count(*) >= 5
<强> Results 强>:
| studentID |
|-----------|
| 549 |
| 990 |
答案 1 :(得分:0)
如果你想要五次缺席:
select s.studentId, count(*)
from tempstudents s
group by s.studentId
having count(*) >= 5;
但是,我怀疑你打算在AttendanceDates
连续5天打算。首先,添加一列来枚举出勤日期:
alter table AttendanceDates add id int;
set @id = 0;
update AttendanceDates
set id = (@id := @id + 1)
order by AttendanceDate;
然后,您想要连续找到五个ID。这是一种方法:
select studentid, count(*), min(currdate), max(currdate)
from (select ads.*,
(@rn := if(@s = studentid, @rn + 1, if(@s := studentid, 1, 1))) as rn
from (select s.*, ad.id
from AttendanceDates ad join
tempstudents s
on s.currdate = ad.AttendanceDate
order by s.studentid, ad.id
) ads cross join
(select @s := 0, @rn := 0) params
) ads
group by s.studentid, (id - @rn)
having count(*) >= 5;
这使用变量来枚举当前日期。然后它取得id
的差异,它识别缺席序列。外部聚合只是将这些计算得到5。