轉自:http://blog.163.com/jeson_lwj/blog/static/135761083201052411115783/
--查詢每門課程的前2名成績
CREATE TABLE StudentGrade(
stuId CHAR(4), --學號
subId INT, --課程號
grade INT, --成績
PRIMARY KEY (stuId,subId)
)
GO
--表中數據如下
INSERT INTO StudentGrade(stuId,subId,grade) VALUES('001',1,97);
INSERT INTO StudentGrade(stuId,subId,grade) VALUES('001',2,50);
INSERT INTO StudentGrade(stuId,subId,grade) VALUES('001',3,70);
INSERT INTO StudentGrade(stuId,subId,grade) VALUES('002',1,92);
INSERT INTO StudentGrade(stuId,subId,grade) VALUES('002',2,80);
INSERT INTO StudentGrade(stuId,subId,grade) VALUES('002',3,30);
INSERT INTO StudentGrade(stuId,subId,grade) VALUES('003',1,93);
INSERT INTO StudentGrade(stuId,subId,grade) VALUES('003',2,95);
INSERT INTO StudentGrade(stuId,subId,grade) VALUES('003',3,85);
INSERT INTO StudentGrade(stuId,subId,grade) VALUES('004',1,73);
INSERT INTO StudentGrade(stuId,subId,grade) VALUES('004',2,78);
INSERT INTO StudentGrade(stuId,subId,grade) VALUES('004',3,87);
GO
/*
要查詢每門課程的前2名成績
001 1 97
003 1 93
003 2 95
002 2 80
004 3 87
003 3 85
如何實現?
*/
--查看數據
select * from StudentGrade
--假如出現並列時,也只取兩個同學的話。
--方法一:
select distinct *
from studentgrade as t1
where stuid in
(select top 2 stuid
from studentgrade as t2
where t1.subid=t2.subid
order by t2.grade desc)
order by subid, grade desc
--方法二:
select * from StudentGrade a where (select count(1) from studentGrade where subId=a.subId and grade>=a.grade)<=2
--方法三:
select * from StudentGrade t
where (select count(1) from StudentGrade where subid=t.subid and grade>t.grade)<=1
order by subId,grade desc
--結果
/*
stuId subId grade
----- ----------- -----------
001 1 97
003 1 93
003 2 95
002 2 80
004 3 87
003 3 85
(6 row(s) affected)
*/
共有三種方案,從難易程度上講我傾向於后兩種,從查詢邏輯思想上來講后兩種是一樣的
select * from StudentGrade t
where (select count(1) from StudentGrade where subid=t.subid and grade>t.grade)<=1
order by subId,grade desc
我是這樣理解的,看成兩張表A和B,條件為A表的學科=B表的學科,select count(1) from StudentGrade where subid=t.subid and grade>t.grade,返回A表的學科=B表的學科並且A表的成績小於B表的成績的影響行數,如果所影響的行數為零說明它的成績是最高的,如果等於1的話就是最高的兩個成績。這就是查詢條件,再按 subId,grade 排序。這種查詢思想很值得我學習
