sql server 分組,取每組的前幾行數據


sql server 分組,取每組的前幾行數據

sql中group by后,獲取每組中的前N行數據,目前我知道的有2種方法

比如有個成績表: 里面有字段學生ID,科目,成績。我現在想取每個科目的頭三名。

  1.   子查詢

select * from score s where StudentName in (
select top 3 StudentName from score where s.Subjects = Subjects 
group by Subjects,StudentName,Score order by Score desc)
group by Subjects,StudentName,Score order by Subjects,Score desc

2.    用rowNumber函數

select Subjects,StudentName,Score from 
(select *,
ROW_NUMBER() over(partition by subjects order by score desc) rowNum
from Score) as s where s.rowNum <= 3
group by Subjects,StudentName,Score order by Subjects,Score desc

 

以上的2種結果都是一樣的。如果還有其他的方法,以后補充

 

 

表和表的數據

Create table Score(StudentName char(10),Subjects char(20), Score float)


insert into Score  values('小明','語文',90),
('小明','數學',80),
('小明','英語',60),
('小紅','語文',93),
('小紅','數學',92),
('小紅','英語',91),
('小花','語文',50),
('小花','數學',30),
('小花','英語',70),
('小草','語文',95),
('小草','數學',86),
('小草','英語',62),
('小剛','語文',78),
('小剛','數學',68),
('小剛','英語',76),
('小柔','語文',56),
('小柔','數學',86),
('小柔','英語',88),
('小陳','語文',77),
('小陳','數學',88),
('小陳','英語',99)

轉載來源:https://blog.csdn.net/u010032648/article/details/51464648


免責聲明!

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



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