关于SQL的over partition by 开窗语句在分页和统计中的使用总
Posted 自由的鱼
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了关于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
以上是关于关于SQL的over partition by 开窗语句在分页和统计中的使用总的主要内容,如果未能解决你的问题,请参考以下文章
T-SQL-Sum over Partition by 与 group by 组合
基于 OVER PARTITION BY 子句的 SQL 计算列
简单的 sql over (partition by) 没有按预期工作
Sql Server Max() over partition by - 翻译成 MySql