下面,我将使用一些表的结构来说明我要执行的操作。
考虑到每个学生的上课时间为30分钟,我想选择学生的时间表,但是我需要对按班级顺序安排的记录进行分组(每个30分钟,无间隔),并且老师和主题是相同的
我正在使用SQL Server 2017。
学生
id name
1 Oliver
2 Jack
3 Harry
老师
id name
1 Amelia
2 Olivia
主题
id subject
1 Mathematics
2 Science
时间表
id startdatetime idstudent idteacher idsubject
1 2019-05-30 08:00 1 1 2
2 2019-05-30 08:40 1 1 2
3 2019-05-30 09:10 1 1 2
3 2019-05-30 09:40 1 2 2
4 2019-05-30 10:10 1 2 1
通过idstudent选择时,我希望将结果按以下分组显示:
Qty startdatetime teacher subject
1 2019-05-30 08:00 Amelia Science
2 2019-05-30 08:40 Amelia Science grouped in a single row(qty 2) because the class time has 30 minutes without interval, teacher and subject are the same.
1 2019-05-30 09:40 Olivia Science
1 2019-05-30 10:10 Olivia Mathematics
谢谢!
答案 0 :(得分:0)
这是一种“群岛问题”。我只关注schedule
表。您可以视需要加入其他表格。
要确定组从何处开始,请使用lag()
。然后,一个累加的总和定义了该组,聚合得到了您想要的:
select count(*) as qty,
idstudent, idteacher, idsubject
from (select s.*,
sum(case when prev_sdt > dateadd(minute, -30, startdatetime)
then 1 else 0
end) over (partition by s.idstudent, s.idteacher, s.idsubject order by s.startdatetime) as grp
from (select s.*,
lag(s.startdatetime) over (partition by s.idstudent, s.idteacher, s.idsubject order by s.startdatetime) as prev_sdt
from schedule s
) s
) s
group by by idstudent, idteacher, idsubject, grp
order by min(startdatetime);