当教师、主题相同且 类 之间没有时间间隔时,对查询进行分组
Group a query when teacher, subject are the same and there is no time interval between classes
下面我将放置一些表的结构来说明我正在尝试做什么。
考虑到每个学生class的时间是30分钟,我想select该学生的课表,但需要对class课表所在的记录进行分组是连续的(每个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 selecting时,我想将结果分组显示如下:
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
提前致谢!
这是一种 group-and-islands 问题。我只关注 schedule
table。您可以根据需要加入其他 table。
要确定组的开始位置,请使用 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);
下面我将放置一些表的结构来说明我正在尝试做什么。
考虑到每个学生class的时间是30分钟,我想select该学生的课表,但需要对class课表所在的记录进行分组是连续的(每个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 selecting时,我想将结果分组显示如下:
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
提前致谢!
这是一种 group-and-islands 问题。我只关注 schedule
table。您可以根据需要加入其他 table。
要确定组的开始位置,请使用 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);