我有一个简单的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上测试我的代码。
答案 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)