-- 開窗函數(shù):在結(jié)果集的基礎(chǔ)上進(jìn)一步處理(聚合操作)
-- Over函數(shù),添加一個(gè)字段顯示最大年齡
SELECT * ,
MAX(StuAge) OVER ( ) MaxStuAge
FROM dbo.Student;
-- Over函數(shù),添加一個(gè)字段顯示總?cè)藬?shù)
SELECT * ,
COUNT(StuID) OVER ( ) StuCount
FROM dbo.Student;
-- Partition By 分組統(tǒng)計(jì)數(shù)量
-- 根據(jù)性別分組后,統(tǒng)計(jì)
SELECT COUNT(*) OVER ( PARTITION BY StuSex ) ,
*
FROM dbo.Student;
-- 根據(jù)班級(jí)分組后,統(tǒng)計(jì)、排序
SELECT COUNT(*) OVER ( PARTITION BY Class ORDER BY Height) ,
*
FROM dbo.Student;
-- Over函數(shù),添加一個(gè)字段顯示平均身高
SELECT * ,
AVG(Height) OVER ( ) AgeHeight
FROM dbo.Student;
--Row_Rumber()
SELECT ROW_NUMBER() OVER ( ORDER BY StuID DESC ) RowNumber ,
*
FROM dbo.Student
--Row_Rumber() 實(shí)現(xiàn)分頁(yè)效果
;
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() 排名函數(shù),名次相同,跳過
SELECT RANK() OVER ( ORDER BY Height ) ,
*
FROM dbo.Student;
--DENSE_Rank() 排名函數(shù),名次相同不跳過
SELECT DENSE_RANK() OVER ( ORDER BY Height ) ,
*
FROM dbo.Student;
-- NTILE()函數(shù),參數(shù):記錄總數(shù)/劃分區(qū)域 = 每個(gè)區(qū)域數(shù)組,把記錄序號(hào)放進(jìn)數(shù)組 (平均分組)
SELECT NTILE(3) OVER ( ORDER BY StuSex ) ,
*
FROM dbo.Student;
以上所述是小編給大家介紹的SQL Server 2012 開窗函數(shù),希望對(duì)大家有所幫助,如果大家有任何疑問歡迎給我留言,小編會(huì)及時(shí)回復(fù)大家的!