Select 每个学生的最高年级和学期
Select top year and term for each student
我想return从这些表中记录每个学生的最后学期。
Table: dbo.Stdetail
StID YearID TermID
2 1 1
3 1 1
3 2 1
3 2 2
3 3 1
3 3 2
4 1 1
4 1 2
5 1 1
5 1 2
Table: dbo.lastyear
StID YearID TermID
1 5 1
2 5 1
2 6 2
3 5 1
3 6 2
我想从这两个表中 return 最终的 yearID 和 term ID。
期望的输出:
StID yearID TermID
1 5 1
2 6 2
3 6 2
4 1 2
5 1 2
我想你想合并 dbo.Stdetail 和 dbo.lastyear,然后应用 row_number()
来识别每个学生的最新记录。像这样:
;with cte as (select *
, row_number() over (partition by StID order by YearID desc, TermID desc) rn
from (select StID, YearID, TermID from dbo.Stdetail
union
select StID, YearID, TermID from dbo.lastyear) x
)
select *
from cte
where rn = 1
我想return从这些表中记录每个学生的最后学期。
Table: dbo.Stdetail
StID YearID TermID
2 1 1
3 1 1
3 2 1
3 2 2
3 3 1
3 3 2
4 1 1
4 1 2
5 1 1
5 1 2
Table: dbo.lastyear
StID YearID TermID
1 5 1
2 5 1
2 6 2
3 5 1
3 6 2
我想从这两个表中 return 最终的 yearID 和 term ID。 期望的输出:
StID yearID TermID
1 5 1
2 6 2
3 6 2
4 1 2
5 1 2
我想你想合并 dbo.Stdetail 和 dbo.lastyear,然后应用 row_number()
来识别每个学生的最新记录。像这样:
;with cte as (select *
, row_number() over (partition by StID order by YearID desc, TermID desc) rn
from (select StID, YearID, TermID from dbo.Stdetail
union
select StID, YearID, TermID from dbo.lastyear) x
)
select *
from cte
where rn = 1