zoukankan      html  css  js  c++  java
  • 关于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

  • 相关阅读:
    WeX5 苹果APP打包教程
    开源中国社区
    HBuilder-飞速编码的极客工具,手指爽,眼睛爽下载
    java用double和float进行小数计算精度不准确
    SQL Server 查询表的主键的两种方式
    JS代码压缩格式化在线地址
    解决SQL Server 阻止了对组件 'Ad Hoc Distributed Queries' 的 STATEMENT'OpenRowset/OpenDatasource' 的访问的方法
    SQL跨数据库复制表数据
    ExtJs 扩展类CheckColumn的使用(事件触发)
    DM36x IPNC OSD显示中文 --- 基本数据准备篇
  • 原文地址:https://www.cnblogs.com/coce/p/7225779.html
Copyright © 2011-2022 走看看