废话不多说了,直接给大家贴代码了,具体代码如下所示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
-- 开窗函数:在结果集的基础上进一步处理(聚合操作)
-- Over函数,添加一个字段显示最大年龄
SELECT * ,
MAX (StuAge) OVER ( ) MaxStuAge
FROM dbo.Student;
-- Over函数,添加一个字段显示总人数
SELECT * ,
COUNT (StuID) OVER ( ) StuCount
FROM dbo.Student;
-- Partition By 分组统计数量
-- 根据性别分组后,统计
SELECT COUNT (*) OVER ( PARTITION BY StuSex ) ,
*
FROM dbo.Student;
-- 根据班级分组后,统计、排序
SELECT COUNT (*) OVER ( PARTITION BY Class ORDER BY Height) ,
*
FROM dbo.Student;
-- Over函数,添加一个字段显示平均身高
SELECT * ,
AVG (Height) OVER ( ) AgeHeight
FROM dbo.Student;
--Row_Rumber()
SELECT ROW_NUMBER() OVER ( ORDER BY StuID DESC ) RowNumber ,
*
FROM dbo.Student
--Row_Rumber() 实现分页效果
;
WITH T AS ( SELECT ROW_NUMBER() OVER ( ORDER BY StuID DESC ) RowNumber ,
*
FROM dbo.Student
)
SELECT *
FROM T
WHERE T.RowNumber BETWEEN 1 AND 3;
--Rank() 排名函数,名次相同,跳过
SELECT RANK() OVER ( ORDER BY Height ) ,
*
FROM dbo.Student;
--DENSE_Rank() 排名函数,名次相同不跳过
SELECT DENSE_RANK() OVER ( ORDER BY Height ) ,
*
FROM dbo.Student;
-- NTILE()函数,参数:记录总数/划分区域 = 每个区域数组,把记录序号放进数组 (平均分组)
SELECT NTILE(3) OVER ( ORDER BY StuSex ) ,
*
FROM dbo.Student;
|
以上所述是小编给大家介绍的SQL Server 2012 开窗函数,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!
原文链接:http://www.cnblogs.com/i-shanghai/p/6351346.html