選出每門學科成績在前2位的記錄,並按照 CourseID 和 Achievement 從高到低排序
-- 建表及插入資料
create table StuTable
(
StudentID varchar(8),
CourseID varchar(10),
Achievement int
)
insert StuTable select 71101, 1, 80
union all select 71102, 4, 86
union all select 71103, 2, 45
union all select 71104, 2, 88
union all select 71102, 1, 90
union all select 71103, 1, 78
union all select 71103, 3, 34
union all select 71104, 3, 64
union all select 71104, 1, 56
union all select 71101, 4, 75
union all select 71101, 2, 76
union all select 71102, 3, 56
union all select 71103, 4, 57
union all select 71102, 2, 85
union all select 71101, 3, 97
union all select 71104, 4, 96
---
Select *
From StuTable a
Where StudentID in (Select Top 2 StudentID From StuTable Where CourseID=a.CourseID Order by Achievement desc)
order by CourseID,Achievement desc
Select * from StuTable A
Where Not Exists(
select 1 from StuTable
Where CourseID=A.CourseID And Achievement>A.Achievement
Having Count(*)>1
)
Order by CourseID,Achievement Desc
drop table StuTable