gpt4 book ai didi

sql - oracle sql : multiple rows in 1 table 中的更新

转载 作者:行者123 更新时间:2023-12-05 00:56:48 24 4
gpt4 key购买 nike

我是 SQL 新手,不擅长更高级的查询和函数。

所以,我有一张销售表:

 id   date         seller_name   buyer_name
---- ------------ ------------- ------------
1 2015-02-02 null Adrian
1 2013-05-02 null John B
1 2007-11-15 null Chris F
2 2014-07-12 null Jane A
2 2011-06-05 null Ted D
2 2010-08-22 null Maryanne A
3 2015-12-02 null Don P
3 2012-11-07 null Chris T
3 2011-10-02 null James O

我要更新 seller_name对于每个 id,通过放置 buyer_name从以前作为卖家名称的销售到较新的销售日期。例如,对于 id 1,John B 将成为 2015-02-02 中的卖家。和买家在 2013-05-02 .那有意义吗?

附言这是一个完美的案例, table 很大,而且 id 没有那么整齐。

最佳答案

merge into your_table a 
using ( select rowid rid,
lead(buyer_name, 1) over (partition by id order by date desc) seller
from your_table
) b
on (a.rowid = b.rid )
when matched then update set a.seller_name= b.seller;

说明: Merge into语句根据匹配或不匹配的条件执行不同的操作。在这里你必须合并到你的表中,在 using具有您想要采用的新值以及将作为匹配键的 rowid。 lead函数根据您在逗号后指定的数字从接下来的 n 行中获取结果。在指定要跳转的行数后,您还可以指定要工作的部分,在您的情况下由 id 分区。并按日期订购,这样您就可以找到之前的买家卖家。希望这能让它变得清晰一点。

关于sql - oracle sql : multiple rows in 1 table 中的更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35596531/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com