这是我的示例数据
RollNo EnrollType EnrollStart EnrollEnd
---------------------------------------------
1 Maths 1/Jan/2019 1/Jan/2020
1 Science 1/Jun/2019 1/Jun/2020
1 Social 2/Jun/2020 2/Jun/2021
在上表中,前两行表示学生在最初假定的结束日期更改了其入学类型。因此,他的首次入学终止日期应为2019年6月1日。
我正在处理的查询是如上所述提取数据。因此摘录应该
1 maths 1/Jan/2019 1/Jun/2019
1 science 1/Jun/2019 1/Jun/2020
1 social 2/Jun/2020 2/Jun/2021
我写的查询是:
Select
rollno, enrolltype, enrollstart,
case
when (select count(*) from student
where enrollstart > s.enrollstart and enrollstart < s.enrollend) > 1
then
(select top 1 enrollstart from student
where enrollstart > s.enrollstart and enrollstart < s.enrollend)
else enrollend
end
from
student s
在生产数据库和实际数据时出现问题,并且此查询两次调用子查询,因此效率似乎不高。提取它的任何更好的方法。
答案 0 :(得分:1)
假设您可以使用lead()/lag()
:
select rollno, enrollstart,
case when enrollend > lead(enrollstart) over (partition by rollno order by enrollstart)
then lead(enrollstart) over (partition by rollno order by enrollstart)
else enrollend
end
from student;