sql 查詢每科的前三名


廢話不多說,直接上腳本 

CREATE TABLE [dbo].[Students](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [name] [nchar](20) NULL,
    [kemu] [nchar](20) NULL,
    [score] [int] NOT NULL,
 CONSTRAINT [PK_Students] PRIMARY KEY CLUSTERED 
(
    [ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
insert into Students values('張三','語文',66)
insert into Students values('李四','語文',67)
insert into Students values('王五','語文',68)
insert into Students values('趙六','語文',69)
insert into Students values('天氣','語文',70)
insert into Students values('王八','語文',72)
insert into Students values('幺九','語文',75)
insert into Students values('大十','語文',80)



insert into Students values('張三','數學',85)
insert into Students values('李四','數學',80)
insert into Students values('王五','數學',75)
insert into Students values('趙六','數學',69)
insert into Students values('天氣','數學',68)
insert into Students values('王八','數學',67)
insert into Students values('幺九','數學',66)
insert into Students values('大十','數學',65)


insert into Students values('張三','英語',60)
insert into Students values('李四','英語',72)
insert into Students values('王五','英語',76)
insert into Students values('趙六','英語',77)
insert into Students values('天氣','英語',85)
insert into Students values('王八','英語',78)
insert into Students values('幺九','英語',75)
insert into Students values('大十','英語',71)

查詢語句:內層中  WHERE B.kemu = A.kemu  其實相當於 拿外層的 name  分組 group  by 

SELECT * 
FROM Students A
WHERE name IN (SELECT TOP 3 name
                       FROM Students B
                      WHERE B.kemu = A.kemu
                      ORDER BY B.score DESC)
ORDER BY A.kemu, A.score DESC

運行結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM