SQL Server - 基于一个col的行号和另一个col的不同值

时间:2017-03-20 16:07:40

标签: sql-server

我的数据看起来像这样

CustomerID  OrderID   Date          Value
100411      00543     06/11/2013    90.75
100411      00543     06/11/2013    81.75
100411      00560     06/11/2013    80.00
100413      00580     06/11/2013    82.34

我可以指定一个行号来对每个客户的订单进行排名:

    SELECT CustomerID, OrderID, 
    ROW_NUMBER() OVER (PARTITION BY CustomerId ORDER BY Date) [PurchaseNumber]
    FROM CustomerOrders

这给了我:

CustomerID  OrderID   PurchaseNumber
100411      00543     1
100411      00543     2
100411      00560     3
100413      00580     1

如果我需要我的排名来对具有相同OrderID的订单进行分组,我该如何实现以下输出?

CustomerID  OrderID   PurchaseNumber
100411      00543     1
100411      00560     2
100413      00580     1

(订单ID:00543仅分为1次购买)

1 个答案:

答案 0 :(得分:1)

如果您要汇总,order by OrderId

select 
    CustomerId
  , OrderId
  , [PurchaseNumber] = row_number() over (partition by CustomerId order by OrderId) 
  , Value = sum(Value)
from CustomerOrders
group by CustomerId, OrderId

返回:

+------------+---------+----------------+--------+
| CustomerId | OrderId | PurchaseNumber | Value  |
+------------+---------+----------------+--------+
|     100411 |   00543 |              1 | 172,50 |
|     100411 |   00560 |              2 | 80,00  |
|     100413 |   00580 |              1 | 82,34  |
+------------+---------+----------------+--------+

如果您没有汇总,请使用dense_rank()

select 
    CustomerId
  , OrderId
  , [PurchaseNumber] = dense_rank() over (partition by CustomerId order by OrderId) 
  , Value
from CustomerOrders

返回:

+------------+---------+----------------+-------+
| CustomerId | OrderId | PurchaseNumber | Value |
+------------+---------+----------------+-------+
|     100411 |   00543 |              1 | 90,75 |
|     100411 |   00543 |              1 | 81,75 |
|     100411 |   00560 |              2 | 80,00 |
|     100413 |   00580 |              1 | 82,34 |
+------------+---------+----------------+-------+

rextester 演示http://rextester.com/OAUJ25435