使用SQL语句的条件等级

时间:2019-05-15 15:51:02

标签: sql sql-server-2016

我必须用两个条件对行进行排名。

| CBorderIID  |  CustomerID | CBDate  | orderID    |OrderDate  |
+-------------+-------------+---------+------------+-----------+
|  355253780  |      5314   |1/29/2017| 355253780  | 1/29/2017 |
|  355253780  |      5314   |1/29/2017| 359324061  | 4/5/2017  |
|  355253780  |      5314   |1/29/2017| 368700530  | 5/16/2017 |
|  355253780  |      5314   |1/29/2017| 375164457  | 9/11/2017 |
|  482387847  |      5384   |1/29/2017| 446421606  | 7/27/2018 |
|  482387847  |      5384   |1/29/2017| 449212357  | 8/5/2018  |
|  482387847  |     5384    |1/29/2017| 482387847  | 1/12/2019 |
|  482387847  |      5384   |1/29/2017| 489428993  | 2/23/2019 |

我想对CBorderIID = OrderID为1的行进行排名,然后在CBorderIID <> OrderID和CBdate

所需的输出

| CBorderIID  |  CustomerID | CBDate  | orderID    |OrderDate  | Rank
+-------------+-------------+---------+------------+-----------+------
|  355253780  |      5314   |1/29/2017| 355253780  | 1/29/2017 | 1
|  355253780  |      5314   |1/29/2017| 359324061  | 4/5/2017  | 2
|  355253780  |      5314   |1/29/2017| 368700530  | 5/16/2017 | 3
|  355253780  |      5314   |1/29/2017| 375164457  | 9/11/2017 | 4
|  482387847  |      5384   |1/29/2017| 446421606  | 7/27/2018 | NULL
|  482387847  |      5384   |1/29/2017| 449212357  | 8/5/2018  | NULL
|  482387847  |     5384    |1/29/2017| 482387847  | 1/12/2019 | 1
|  482387847  |      5384   |1/29/2017| 489428993  | 2/23/2019 | 2

我尝试了在OrderID上进行分区的条件下进行行排序,但是它不起作用。

2 个答案:

答案 0 :(得分:0)

我认为这是您想要的逻辑:

select t.*
       (case when CBdate < O.orderdate
             then rank() over (partition by CBorderIID
                               order by ((case when CBorderIID = orderID then 1 else 2 end),
                                         OrderDate
                                        ) as rank
        end)
from t;

注意:如果没有任何匹配的CBorderIID = orderID,则第一个订购日期的排名将为1。如果多个匹配,则所有订单的排名将为1。

这些与您对问题的表述方式一致,但是还有其他可能性。

答案 1 :(得分:0)

您可以将row_number()与已定义的组一起使用:

select t.*, 
      (case when grp = 1 and CBdate <= orderdate 
            then row_number() over (partition by CBorderIID, CustomerID, grp order by OrderDate)
       end) as Rank
from (select t.*, 
             sum(case when CBorderIID = orderID then 1 else 0 end) over (partition by CBorderIID, CustomerID order by orderdate) as grp
      from table t
     ) t;