zoukankan      html  css  js  c++  java
  • SQL ROW_NUMBER() 排序函数

    1使用row_number()函数进行编号:如

    select email,customerID, ROW_NUMBER() over(order by psd) as rows from QT_Customer
    

      

    原理:先按psd进行排序,排序完后,给每条数据进行编号。

    2.在订单中按价格的升序进行排序,并给每条记录进行排序

    代码如下:

    select DID,customerID,totalPrice,ROW_NUMBER() over(order by totalPrice) as rows from OP_Order
    

      

    3.统计出每一个各户的所有订单并按每一个客户下的订单的金额 升序排序,同时给每一个客户的订单进行编号。这样就知道每个客户下几单了。

     如图:

    代码如下:

    select ROW_NUMBER() over(partition by customerID  order by totalPrice) as rows,customerID,totalPrice, DID from OP_Order
    

      

     4.统计每一个客户最近下的订单是第几次下的订单。

     代码如下:

    with tabs as
     (
     select ROW_NUMBER() over(partition by customerID  order by totalPrice) as rows,customerID,totalPrice, DID from OP_Order
     )
     
     select MAX(rows) as '下单次数',customerID from tabs group by customerID
    

      

     5.统计每一个客户所有的订单中购买的金额最小,而且并统计改订单中,客户是第几次购买的。

    如图:

    上图:rows表示客户是第几次购买。 

    思路:利用临时表来执行这一操作

     1.先按客户进行分组,然后按客户的下单的时间进行排序,并进行编号。

     2.然后利用子查询查找出每一个客户购买时的最小价格。

     3.根据查找出每一个客户的最小价格来查找相应的记录。 

    代码如下:

    View Code 1 with tabs as
     (
     select ROW_NUMBER() over(partition by customerID  order by insDT) as rows,customerID,totalPrice, DID from OP_Order
     )
     select * from tabs
      where totalPrice in 
                (
                select MIN(totalPrice)from tabs group by customerID
                )
    

      

     5.筛选出客户第一次下的订单。

    思路。利用rows=1来查询客户第一次下的订单记录。 

    代码如下:

    View Code 1 with tabs as
     (
     select ROW_NUMBER() over(partition by customerID  order by insDT) as rows,* from OP_Order
     )
     select * from tabs where rows = 1
       
     select * from OP_Order
    

      

     6.rows_number()可用于分页

     思路:先把所有的产品筛选出来,然后对这些产品进行编号。然后在where子句中进行过滤。 

     7.注意:在使用over等开窗函数时,over里头的分组及排序的执行晚于“where,group by,order by”的执行。

                如下代码:

    select 
      ROW_NUMBER() over(partition by customerID  order by insDT) as rows,
      customerID,totalPrice, DID
      from OP_Order where insDT>'2011-07-22'
    

      

       以上代码是先执行where子句,执行完后,再给每一条记录进行编号。

  • 相关阅读:
    js call
    正则简单学习
    第10天:apply和call、bind、函数作为参数、返回值使用、闭包、递归的样例
    第9天:原型、继承、函数使用推荐以及this的指向
    Identity Server introspect 调用 /connect/introspect
    windows forget jenkins password.
    转载(Asp.net Core 中试使用ZKWeb.System.Drawing)
    EFCore & Mysql migration on Production
    HTML to PDF pechkin
    Log4net
  • 原文地址:https://www.cnblogs.com/ShaYeBlog/p/2693173.html
Copyright © 2011-2022 走看看