SQL 更新最后一次出现

SQL update last occurrence

我有一个简单的 SELECT 查询运行良好,returns 一行,这是 order_id 列中特定值的最后一次出现。我想更新这一行。但是,我无法将此 SELECT 查询与 UPDATE 查询结合使用。

这是 returns 一行的工作查询,我想更新它:

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 *,并更新 table 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.

测试我的代码

尝试这样的事情。我不确定 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 

测试下面的查询

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)

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
     );