我正在尝试根据以下两个表生成报告:
Name Start Year End Year No. Of Students Fill Order
School-ABC 2000 2004 1 1
School-DEF 2000 2004 2 3
School-GHI 2000 2004 1 2
Name Start Year End Year Joined On
Student-1 2000 2004 01-Jan
Student-2 2000 2004 03-Jan
Student-3 2000 2004 02-Jan
Student-4 2000 2004 15-Jan
预期产出低于:
Name Start Year End Year Joined On School
Student-1 2000 2004 01-Jan School-ABC
Student-2 2000 2004 03-Jan School-DEF
Student-3 2000 2004 02-Jan School-GHI
Student-4 2000 2004 15-Jan School-DEF
生成数据背后的逻辑:
在分析问题一段时间之后,我得出结论,单独使用选择查询可能无法实现这一点。目前,我计划为每个表使用两个游标并逐行处理记录。有没有更好的方法,或通过选择语句可以吗? TIA
注意:
答案 0 :(得分:1)
您可以使用Oracle分析功能。 row_number() over ()
可以根据加入日期为每位学生分配一个号码。 sum() over ()
可以计算每所学校的第一个和最后一个学生。结合你得到的两个:
select stud.name
, stud.startyear
, stud.endyear
, stud.joinedon
, schl.name as SchoolName
from (
select name
, coalesce(sum(NoOfStudents) over (order by FillOrder
range between unbounded preceding and 1 preceding),0)+1 FirstStudent
, sum(NoOfStudents) over (order by FillOrder) as LastStudent
from Schools
) schl
join (
select row_number() over (order by JoinedOn) as StudentRank
, Students.*
from Students
) stud
on stud.StudentRank between schl.FirstStudent and schl.LastStudent
order by
stud.name