序列化表格详细信息

时间:2017-05-16 20:29:36

标签: sql sql-server group-by

我正在使用SQL Server 2012,我想使用更新语句重新排列下面的订单号,但为每个订单行保留相同的订单号

order_date  Order_Number  Order_Line
-------------------------------------
2015-01-06      1               1
2015-01-06      1               2
2015-01-06      6               1
2015-01-06      6               2
2015-01-06      9               1
2015-01-06      9               2
2015-01-06      9               3
2015-01-06      11              1
2015-01-06      11              2
2015-01-06      11              3
2015-01-06      11              4

我试过这个:

DECLARE @OrdN INT = 0 

UPDATE hist_line 
SET @OrdN = order_number = @OrdN + 1 
WHERE order_date = '06/01/2015'

但它为每一行返回一个新的序列,它应该如下所示:

order_date  Order_Number  Order_Line
-------------------------------------
2015-01-06      1               1
2015-01-06      1               2
2015-01-06      2               1
2015-01-06      2               2
2015-01-06      3               1
2015-01-06      3               2
2015-01-06      3               3
2015-01-06      4               1
2015-01-06      4               2
2015-01-06      4               3
2015-01-06      4               4

1 个答案:

答案 0 :(得分:3)

您可以使用dense_rank()

select order_date,
       dense_rank() over (partition by order_date order by Order_Number) as Order_Number,
       Order_Line
from t;

这是一个ANSI标准函数,可在大多数数据库中使用。

编辑:

要实际执行更新,请使用可更新的CTE:

with toupdate as (
      select t.*,
             dense_rank() over (partition by order_date order by Order_Number) as new_Order_Number
      from t
     )
update toupdate
    set Order_Number = new_Order_Number;