-1

如何连接事务表和 SCD 表以根据事务日期从 SCD 获取记录。

Select A.id, A.trans_dt, trans_amt, B.pmt_meth
from trans1 A
left join scd1 B
  on A.id=B.id

现在我需要为每笔交易获取 pmt_meth。所以前 2 个交易的 pmt_meth 应该是“M”,最后一个交易应该是“P”

由于加入问题,这正在创建重复项(我知道),但不确定如何匹配日期,以便不会创建重复项,我将获得所需的结果

create table scd1 (id integer, pmt_meth varchar (10), start_dt date, end_dt date)

Insert into scd1(1, P, '2015/06/30', '2017/05/30')
Insert into scd1(1, M, '2017/05/30', '2019/07/31')
Insert into scd1(1, P, '2019/07/31', '2050/12/31')

Create table trans1 (id integer, trans_dt date, trans_amt float)
Insert into trans1 (1, '2019/07/25', 100)
Insert into trans1 (1, '2019/07/01', 120)
Insert into trans1 (1, '2019/07/31', 50)

现在我需要为每笔交易获取 pmt_meth。所以前 2 个交易的 pmt_meth 应该是“M”,最后一个交易应该是“P”

Select A.id, A.trans_dt, trans_amt, B.pmt_meth
from trans1 A
left join scd1 B
  on A.id=B.id

预期结果是

id trans_dt      trans_amt    pmt_meth
1  '2019/07/25'  100            M
1  '2019/07/01'  120            M
1  '2019/07/31'  50             P
4

2 回答 2

0

您的实现基于一个包含-排除间隔:

Select A.id, A.trans_dt, trans_amt, B.pmt_meth
from trans1 A
left join scd1 B
  on A.id=B.id
 and A.trans_dt >= B.start_dt 
 and A.trans_dt < B.end_dt

同样的逻辑也适用于 OVERLAPS 算子

Select A.id, A.trans_dt, trans_amt, B.pmt_meth
from trans1 A
left join scd1 B
  on A.id=B.id
 and (A.trans_dt, NULL) OVERLAPS (B.start_dt, B.end_dt)

顺便说一句,Teradata 支持临时表(在 Teradata 加上标准 SQL 语法中)以简化的方式实现 SCD2。

于 2019-08-22T14:50:47.133 回答
0

只需在on子句中包含日期条件:

Select A.id, A.trans_dt, A.trans_amt,
       B.pmt_meth      
from trans1 A left join
     scd1 B
     on A.id = B.id and
        A.trans_dt bewteen b.start_dt and b.end_dt;
于 2019-08-22T14:22:43.990 回答