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

  • 相关阅读:
    hdu 1253 胜利大逃亡 (三维简单bfs+剪枝)
    OpenCV中OpenCL模块函数
    基于年纪和成本(Age & Cost)的缓存替换(cache replacement)机制
    POJ 1637 混合图求欧拉回路 最大流实现
    Linux-shell-算术运算{expr、bc、dc、(( ))和[ ]}
    uboot环境变量与内核MTD分区关系
    nor flash 和nand flash 的区别
    NAND Flash大容量存储器K9F1G08U的坏块管理方法
    嵌入式学习之Nand Flash
    s3c2440对nandflash的操作
  • 原文地址:https://www.cnblogs.com/coce/p/7225779.html
Copyright © 2011-2022 走看看