使用同一个表中的另一列更新表

时间:2016-06-21 17:33:14

标签: sql oracle

我有一张这样的表

Test_order

    Order Num    Order ID   Prev Order ID
    987Y7OP89    919325     0
    987Y7OP90    1006626    919325
    987Y7OP91    1029350    1006626
    987Y7OP92    1756689    0
    987Y7OP93    1756690    0
    987Y7OP94    1950100    1756690
    987Y7OP95    1977570    1950100
    987Y7OP96    2160462    1977570
    987Y7OP97    2288982    2160462

目标表应如下所示,

Order Num   Order ID    Prev Order ID
987Y7OP89   919325      0
987Y7OP90   1006626     919325
987Y7OP91   1029350     1006626
987Y7OP92   1756689     1029350
987Y7OP93   1756690     1756689
987Y7OP94   1950100     1756690
987Y7OP95   1977570     1950100
987Y7OP96   2160462     1977570
987Y7OP97   2288982     2160462
987Y7OP97   2288900     2288982

上一个订单ID应该使用同一个表中上一个记录中的订单ID进行更新。

我正在尝试创建一个虚拟数据集并进行更新..但它无法正常工作..

WITH A AS
(SELECT ORDER_NUM, ORDER_ID, PRIOR_ORDER_ID,ROWNUM RID1 FROM TEST_ORDER),B AS (SELECT ORDER_NUM, ORDER_ID, PRIOR_ORDER_ID,ROWNUM+1 RID2 FROM TEST_ORDER)
SELECT A.ORDER_NUM,B.ORDER_ID,A.PRIOR_ORDER_ID,B.PRIOR_ORDER_ID FROM A,B WHERE RID1 = RID2

2 个答案:

答案 0 :(得分:1)

您可以使用Oracles Analytical Functions(也称为窗口函数)从上一个订单中获取值:

UPDATE Test_Order 
SET ORDERID = LAG(ORDERID, 1, 0) OVER (ORDER BY ORDERNUM ASC) 
WHERE PrevOrderId = 0

See here for the documentation on LAG()

答案 1 :(得分:0)

在sql-server中你不能在update语句中使用window函数,不是正面的,但在Oracle中也不这么认为。无论如何,你可以更新一个cte,如下所示。

WITH cte AS (
    SELECT
       *
       ,NewPreviousOrderId = LAG(OrderId,1,0) OVER (ORDER BY OrderNum)
    FROM
       TableName
)

UPDATE cte
    SET PrevOrderId = NewPreviousOrderId

如果你想坚持使用ROW_NUMBER路线,那就是这样做的方式。

;WITH cte AS (
    SELECT
       *
       ,ROW_NUMBER() OVER (ORDER BY OrderNum) AS RowNum 
    FROM
       TableName
)

UPDATE c1
    SET PrevOrderId = c2.OrderId
FROM
    cte c1
    INNER JOIN cte c2
    ON (c1.RowNum - 1) = c2.RowNum