[英]Sql Update query with self join on SCD2
I am facing an issue with SQL update query in with self join.我在使用自联接时遇到了 SQL 更新查询的问题。 I have looked into multiple pages here but didn't find the right solution.我在这里查看了多个页面,但没有找到正确的解决方案。
Suppose I have a table like below.假设我有一张如下表。
id ID | country国家 | city城市 | timestamp时间戳 |
---|---|---|---|
1 1 | |||
1 1 | India印度 | Pune浦那 | 222 222 |
1 1 | India印度 | Delhi德里 | 111 111 |
I want to copy country and city from the max(timestamp)
row where they are not null ( group by id
).我想从max(timestamp)
行复制国家和城市,它们不是 null ( group by id
)。
I was trying below query which obviously needs correction.我正在尝试下面的查询,这显然需要更正。
update a1
set a1.country = a2.country,
a1.city = a2.city
from selfjointable a1
inner join selfjointable a2 on (a1.id = a2.id)
where a1.country is null
and a2.country is not null
and a2.timestamp = (select max(a3.timestamp)
from selfjointable a3
where (a3.id = a1.id)
group by a3.id);
Please note: This is just simplified version of my issues and there are numbers of rows and column and I just want to write generic update query for all of these rows请注意:这只是我的问题的简化版本,有很多行和列,我只想为所有这些行编写通用更新查询
How about merge
? merge
怎么样?
SQL> select * from test order by id, timestamp desc nulls last;
ID COUNTRY CITY TIMESTAMP
---------- ------- ------ ----------
1 India Pune 222 --> MAX timestamp for ID = 1; these values ...
1 India Delhi 111
1 --> ... should be copied here
2 Croatia Zagreb 333
SQL> merge into test a
2 using (select id, country, city, timestamp,
3 row_number() over (partition by id order by timestamp desc nulls last) rn
4 from test
5 ) x
6 on (x.id = a.id and x.rn = 1)
7 when matched then update set
8 a.country = x.country,
9 a.city = x.city,
10 a.timestamp = x.timestamp
11 where a.country is null;
1 row merged.
SQL> select * from test order by id, timestamp desc nulls last;
ID COUNTRY CITY TIMESTAMP
---------- ------- ------ ----------
1 India Pune 222
1 India Pune 222
1 India Delhi 111
2 Croatia Zagreb 333
SQL>
Below query worked:以下查询有效:
UPDATE selfjointable a1
SET (a1.country, a1.city) = (
SELECT a2.country, a2.city
FROM selfjointable a1
WHERE (a1.id=a2.id)
AND a2.timestamp = (
SELECT max(a3.timestamp)
FROM selfjointable a3
WHERE (a3.id = a2.id) Group by a3.id
)
)
WHERE a1.country is null
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.