我有两个跟踪数据库值更改的历史记录表,使用修订ID来跟踪各个更改.例如
表格1:
rev | A | B
=================
1 | 100 | 'A'
4 | 150 | 'A'
7 | 100 | 'Z'
Run Code Online (Sandbox Code Playgroud)
表2:
rev | C | D
==================
1 | 200 | True
5 | 0 | True
8 | 0 | False
Run Code Online (Sandbox Code Playgroud)
目标是将两个表合并为:
rev | A | B | C | D
===============================
1 | 100 | 'A' | 200 | True
4 | 150 | 'A' | 200 | True
5 | 150 | 'A' | 0 | True
7 | 100 | 'Z' | 0 | True
8 | 100 | 'Z' | 0 | False
Run Code Online (Sandbox Code Playgroud)
这个想法是,对于给定的修订,我会采用与该修订相对应的值或者低于它的最高修订版.
想到的SQL查询类似于使用约束rev1 <rev2交叉连接两个表,然后使用子查询选择行,其中rev1 = max(rev1 )用于每个给定的rev2 ; unioning此查询与其对应交换转2和REV1 ; 最后过滤掉rev1 = rev2的副本.
问题是:
select
coalesce(t1.rev, t2.rev) rev,
coalesce(a, lag(a, 1) over(order by coalesce(t2.rev, t1.rev))) a,
coalesce(b, lag(b, 1) over(order by coalesce(t2.rev, t1.rev))) b,
coalesce(c, lag(c, 1) over(order by coalesce(t1.rev, t2.rev))) c,
coalesce(d, lag(d, 1) over(order by coalesce(t1.rev, t2.rev))) d
from
t1
full join
t2 on t1.rev = t2.rev
order by rev
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
135 次 |
| 最近记录: |