关于SQL的over partition by 开窗语句在分页和统计中的使用总

CREATE TABLE OrderInfo(
ID INT IDENTITY(1,1) PRIMARY KEY,
CustomerID INT NULL,
TotalMoney DECIMAL(18,2) NULL,
OrderStatus TINYINT NULL DEFAULT 0,
CreateTime DATETIME DEFAULT GETDATE() NOT NULL
)

INSERT INTO OrderInfo
(
CustomerID,
TotalMoney,
OrderStatus,
CreateTime
)
SELECT 1,100,1,'2015-03-21' UNION ALL
SELECT 2,50,1,'2015-03-22' UNION ALL
SELECT 1,300,1,'2015-03-23' UNION ALL
SELECT 3,1000,3,'2015-03-24' UNION ALL
SELECT 2,20,1,'2015-03-24' UNION ALL
SELECT 5,50,4,'2015-03-20' UNION ALL
SELECT 8,600,2,'2015-03-21' UNION ALL
SELECT 6,80,1,'2015-03-22' UNION ALL
SELECT 2,70,1,'2015-03-23' UNION ALL
SELECT 1,40,0,'2015-03-23' UNION ALL
SELECT 9,20,1,'2015-03-20' UNION ALL
SELECT 10,100,1,'2015-03-21' UNION ALL
SELECT 6,99,1,'2015-03-24' UNION ALL
SELECT 4,78,2,'2015-03-25' UNION ALL
SELECT 2,100,1,'2015-03-24'

/*
找出每个顾客第一次下单的时间及金额
*/
with cte as(
select *,ROW_NUMBER() over(partition by customerid order by createtime) rm from OrderInfo
)
select * from cte where rm=1 --select CustomerID,min(CreateTime) from OrderInfo group by CustomerID

/*
找出每个顾客金额最大的订单金额
*/
with cte as(
select *,ROW_NUMBER() over(partition by customerid order by totalmoney desc) rm from OrderInfo
)
select * from cte where rm=1 ---select CustomerID,max(TotalMoney) from OrderInfo group by CustomerID

/*
统计每一个客户最近下的订单是第几次下的订单
*/
with cte as
(
select *,ROW_NUMBER() over(partition by customerid order by createtime) rm from OrderInfo
)select CustomerID,max(rm) from cte
group by CustomerID ---select CustomerID,count(CustomerID) from OrderInfo group by CustomerID

/*
统计所有客户第3次下单订单信息
*/
;with cte as(
select *,ROW_NUMBER() over(partition by customerid order by createtime) rm from OrderInfo
)
select * from cte where rm=3

/*
统计每一个客户所有订单金额的平均值
*/
select *,avg(TotalMoney) over(partition by customerid) rm from OrderInfo

/*
在使用over等开窗函数时,over里头的分组及排序的执行晚于“where,group by,order by”的执行。
*/
SELECT CustomerID,CreateTime,ROW_NUMBER() OVER (PARTITION BY customerID ORDER BY CreateTime) AS num
FROM OrderInfo
WHERE CustomerID>2

原文地址:https://www.cnblogs.com/coce/p/7225779.html