oracle sql使用分析函数更新行

时间:2018-04-17 15:45:53

标签: sql oracle

我有一张包含以下数据的表格

PRODUCT_ID  ORDER_DATE  NEW_ORDER_DATE
1000       2007/09/15   NULL
1000       2007/09/17   Null
1000       2007/09/20   Null
1000       2007/09/23   Null
1000       2007/09/25   Null
1000       2007/09/27   Null

我必须使用以下数据更新new_order_date

PRODUCT_ID  ORDER_DATE  NEW_ORDER_DATE
1000       2007/09/15   2007/09/16
1000       2007/09/17   2007/09/19
1000       2007/09/20   2007/09/22
1000       2007/09/23   2007/09/24
1000       2007/09/25   2007/09/26
1000       2007/09/27   2100/01/01

如您所见,new_order_date总是基于使用date-1的相同product_id的下一行order_date计算,最后一行更新为默认日期2100/01/01。如果有任何可用于实现此功能的功能,请你告诉我

2 个答案:

答案 0 :(得分:1)

使用LEAD功能和相关更新。

UPDATE product p1
SET NEW_ORDER_DATE = (
        SELECT new_order_date
        FROM (
            SELECT PRODUCT_ID
                ,ORDER_DATE
                ,LEAD(ORDER_DATE, 1, DATE '2100-01-01' + 1) OVER (
                    PARTITION BY PRODUCT_ID ORDER BY ORDER_DATE
                    ) - 1 AS new_order_date
            FROM product
            ) p2
        WHERE p1.PRODUCT_ID = p2.product_id
            AND p1.ORDER_DATE = p2.ORDER_DATE
        );

Demo

答案 1 :(得分:0)

我会这样做:

update product p
    set new_order_date = (select max(order_date) keep (dense_rank first order by order_date)
                          from product p2
                          where p2.product_id = p.product_id
                         );

这实际上将最后一个值保留为NULL。可以使用coalesce()轻松修复:

update product p
    set new_order_date = (select coalesce(max(order_date) keep (dense_rank first order by order_date), date '2100-01-01')
                          from product p2
                          where p2.product_id = p.product_id
                         );