SQL -- 使用PARTITION和RANK函数完成统计
有时需要对查询结果集进行内部分组,或统计排名,这时PARTITION和RANK非常有用。下例以学生成绩表为例,演示一下用法:
1 创建测试表:
CREATE TABLE [dbo].[StudentScore](
[Id] [int] NOT NULL,
[Name] [nvarchar](20) NULL,
[ClassId] [int] NOT NULL,
[Subject] [nvarchar](20) NULL,
[Score] [decimal](18, 0) NULL
) ON [PRIMARY]
GO
表说明:
name: 学生名字
classId: 班级id
subject: 科目
score : 分数
查询实例1: 统计学生总分,科目总分,班级总分。
-- use SUM + Partition to stastic total score
select s.Name,classId,
SUM(s.Score) OVER (PARTITION BY name) as StudentTotalScore,
SUM(s.Score) OVER (PARTITION BY Subject) as SubjectTotalScore,
SUM(s.Score) OVER (PARTITION BY classId) as ClassTotalScore
FROM StudentScore s
order by StudentTotalScore
查询实例2: 统计学生总分,并按照学生总成绩进行排名(不区分班级)。
-- use SUM() + RANK() stastic student total score and ranking
select s.Name,classid,
SUM(s.Score),
RANK() OVER (ORDER BY SUM(s.Score) DESC ) as Ranking
FROM StudentScore s
group by s.Name,classid
查询实例3: 统计学生总分,按总成绩排名,并区分班级。
-- use SUM() + RANK() + PARTITION to stastic total score and ranking for individule class Id
select s.Name,classid,
SUM(s.Score),
RANK() OVER (PARTITION BY classid ORDER BY SUM(s.Score) DESC ) as Ranking
FROM StudentScore s
group by s.Name,classid