SQL更新最后一次出现

时间:2015-02-20 10:35:33

标签: sql database postgresql sql-update

我有一个简单的SELECT查询可以正常工作并返回一行,这是order_id列中特定值的最后一次出现。我想更新这一行。但是,我无法将此SELECT查询与UPDATE查询结合使用。

这是返回一行的工作查询,我想要更新:

SELECT *
FROM (
       SELECT *,
              ROW_NUMBER() OVER(PARTITION BY order_id
       ORDER BY start_hour DESC) rn
       FROM general_report
       WHERE order_id = 16836
     ) q
WHERE rn = 1

我尝试了很多组合来更新此语句返回的行。例如,我尝试删除SELECT *,并按照以下内容更新表q,但它没有告诉我关系q不存在。

UPDATE  q
SET q.cost = 550.01685
FROM (
       SELECT *,
              ROW_NUMBER() OVER(PARTITION BY order_id
       ORDER BY start_hour DESC) rn
       FROM general_report
       WHERE order_id = 16836
     ) q
WHERE rn = 1

如何将这些代码与正确的UPDATE语法结合起来?如果需要,我在SQL Manager for PostgreSQL上测试我的代码。

3 个答案:

答案 0 :(得分:1)

尝试这样的事情。我不确定PostgreSQL语法:

UPDATE general_report AS d 
SET cost  = 550.01685
FROM (
       SELECT *
       FROM (
              SELECT *,
              ROW_NUMBER() OVER(PARTITION BY order_id
              ORDER BY start_hour DESC) rn
              FROM general_report
              WHERE order_id = 16836
             ) q
        WHERE rn = 1
     ) s
WHERE d.id = s.id 

答案 1 :(得分:1)

update the most recent record的另一种方法是使用NOT EXISTS (even more recent)

UPDATE  general_report dst
SET cost = 550.01685
WHERE order_id = 16836
AND NOT EXISTS (
       SELECT *
       FROM general_report nx
       WHERE nx.order_id = dst.order_id
       AND  nx.start_hour > dst.start_hour
     );

答案 2 :(得分:0)

测试以下查询

UPDATE  q
SET q.cost = 550.01685
where id in  
(select id from
(
       SELECT *
              ROW_NUMBER() OVER(PARTITION BY order_id
       ORDER BY start_hour DESC) rn
       FROM general_report
       WHERE order_id = 16836
     ) q
WHERE rn = 1)