在填充值时合并两个版本跟踪表

Nan*_*n L 8 sql postgresql

我有两个跟踪数据库值更改的历史记录表,使用修订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此查询与其对应交换转2REV1 ; 最后过滤掉rev1 = rev2的副本.

问题是:

  • 这种类型的加入是否有名称?
  • 是否有在SQL中执行此类连接的习惯用法,或者以编程方式执行此操作会更好(这肯定会更简单,也可能更高效)?

Clo*_*eto 2

SQL小提琴

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)