简体   繁体   English

您可以在 where 子句中使用分区更新表吗?

[英]Can you update a table using a partition within the where clause?

I have a query:我有一个问题:

SELECT *, ORDER = MAX(ORDER) OVER (PARTITION BY ID)
FROM MY TABLE

Where MY_TABLE is currently MY_TABLE 目前在哪里

ID ID ORDER命令 AGE年龄 RECENT最近的
12 12 34 34 50 50 TRUE真的
99 99 41 41 17 17 TRUE真的
12 12 34 34 24 24 TRUE真的
99 99 42 42 12 12 TRUE真的
12 12 33 33 15 15 TRUE真的
12 12 33 33 38 38 TRUE真的

I want the table to be updated as the result from the query to be我希望将表更新为查询结果

ID ID ORDER命令 AGE年龄 RECENT最近的
12 12 34 34 50 50 TRUE真的
99 99 41 41 17 17 FALSE错误的
12 12 34 34 24 24 TRUE真的
99 99 42 42 12 12 TRUE真的
12 12 33 33 15 15 FALSE错误的
12 12 33 33 38 38 FALSE错误的

Is there a way to do this with an UPDATE statement.有没有办法用 UPDATE 语句来做到这一点。

I was trying我在尝试

UPDATE MY_TABLE
SET RECENT = FALSE
WHERE ORDER <> MAX(ORDER) OVER (PARTITION BY ID);

But I am not sure how to incorporate the partition statement into the update.但我不确定如何将分区语句合并到更新中。

Try this:试试这个:

update my_table
set recent = false
where (id, order) not in (select id, max(order) from my_table group by 1); 

As suggested by @Tim Biegeleisen, running this as an update may not be the best idea.正如@Tim Biegeleisen 所建议的那样,将其作为更新运行可能不是最好的主意。 Rather than updating the table you could create a view over the top of it to always show the latest information, without needing to update the table.您可以在其顶部创建一个视图以始终显示最新信息,而不需要更新表格,而不是更新表格。 This removes the risk of the RECENT column going out of date between new values being added, and the update process being executed.这消除了在添加新值和执行更新过程之间RECENT列过时的风险。

CREATE TABLE my_tbl (id NUMBER, "ORDER" NUMBER, age NUMBER);

INSERT INTO my_tbl VALUES 
(12, 34, 50),
(99, 41, 17),
(12, 34, 24),
(99, 42, 12),
(12, 33, 15),
(12, 33, 38);

CREATE OR REPLACE VIEW my_view AS
SELECT
    *,
    "ORDER" = MAX("ORDER") OVER (PARTITION BY ID) AS RECENT
FROM
    my_tbl
;

This gives the output:这给出了 output:

ID ID ORDER命令 AGE年龄 RECENT最近的
12 12 34 34 50 50 TRUE真的
99 99 41 41 17 17 FALSE错误的
12 12 34 34 24 24 TRUE真的
99 99 42 42 12 12 TRUE真的
12 12 33 33 15 15 FALSE错误的
12 12 33 33 38 38 FALSE错误的

Adding another row:添加另一行:

INSERT INTO my_tbl VALUES (12, 35, 51);

Gives:给出:

ID ID ORDER命令 AGE年龄 RECENT最近的
12 12 34 34 50 50 FALSE错误的
99 99 41 41 17 17 FALSE错误的
12 12 34 34 24 24 FALSE错误的
99 99 42 42 12 12 TRUE真的
12 12 33 33 15 15 FALSE错误的
12 12 33 33 38 38 FALSE错误的
12 12 35 35 51 51 TRUE真的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM