我需要根据事务日期从Table2接收一个标志...我在表1和table2之间做了一个左外连接。我在左外连接后创建了2个计算字段:
Cal_Validfrom - If Validityfrom is null then 10000101 else Validityfrom end
Cal_ValidTo - If ValidityTo is null then 99991231 else Validityfrom end
我会过滤计算字段和交易日期
案例1)
Table 1 -> Transaction ID Transaction Date Price
123 02/15/2017 $100
Table 2 -> Transaction ID ValidityFrom ValidityTo Flag
123 01/01/2017 01/15/2017 A
123 01/16/2017 02/01/2017 B
123 02/02/2017 12/31/9999 C
加入后
Transaction ID Transaction Date Price ValidityFrom ValidityTo Flag Cal_Validfrom Cal_ValidTo
123 02/15/2017 $100 01/01/2017 01/15/2017 A 01/01/2017 01/15/2017
123 02/15/2017 $100 01/16/2017 02/01/2017 B 01/16/2017 02/01/2017
123 02/15/2017 $100 02/02/2017 12/31/9999 C 02/02/2017 12/31/9999
然后过滤Cal_Validfrom< =交易日期< = Cal_ValidTo
Transaction ID Transaction Date Price ValidityFrom ValidityTo Flag Cal_Validfrom Cal_ValidTo
123 02/15/2017 $100 02/02/2017 12/31/9999 C 02/02/2017 12/31/9999
情况2)
Table 1 -> Transaction ID Transaction Date Price
123 02/15/2017 $100
Table 2 -> ValidityFrom ValidityTo
No Records
加入后
Transaction ID Transaction Date Price ValidityFrom ValidityTo Flag Cal_Validfrom Cal_ValidTo
123 02/15/2017 $100 Null Null Null 01/01/1000 12/31/9999
然后过滤Cal_Validfrom< =交易日期< = Cal_ValidTo
Transaction ID Transaction Date Price ValidityFrom ValidityTo Flag Cal_Validfrom Cal_ValidTo
123 02/15/2017 $100 Null Null Null 01/01/1000 12/31/9999
情形3)
Table 1 -> Transaction ID Transaction Date Price
123 02/15/2017 $100
Table 2 -> Transaction ID ValidityFrom ValidityTo Flag
123 01/01/2017 01/15/2017 A
123 01/16/2017 02/01/2017 B
加入后
Transaction ID Transaction Date Price ValidityFrom ValidityTo Flag Cal_Validfrom Cal_ValidTo
123 02/15/2017 $100 01/01/2017 01/15/2017 A 01/01/2017 01/15/2017
123 02/15/2017 $100 01/16/2017 02/01/2017 B 01/16/2017 02/01/2017
然后过滤Cal_Validfrom< =交易日期< = Cal_ValidTo
Transaction ID Transaction Date Price ValidityFrom ValidityTo Flag Cal_Validfrom Cal_ValidTo
问题出在案例3中 - 我仍然需要查看交易 - 我不能松开交易或复制交易。
任何建议
答案 0 :(得分:0)
问题是您在联接后过滤,这可能会消除交易记录。 为了解决这个问题,你需要做一个左外连接,一个已经过滤的表,让我们调用那个表table2'。 表2'是table2和table1之间(正常)连接的结果,您应用过滤器。由于您没有提供架构,我将用此说明:
select t1.[Transaction ID], t1.[Transaction Date], t1.[Price],
t2.[Transaction ID], t2.ValidityFrom , t2.ValidityTo, t2.Flag
from table1 t1
left outer join table2 t2 on t1.[Transaction ID] = t2.[Transaction ID]
where
t2.ValidityFrom <= [Transaction Date]
and [Transaction Date] <= t2.ValidityTo
-- SHOULD BECOME:
select t1.[Transaction ID], t1.[Transaction Date], t1.[Price],
t2.[Transaction ID], t2.ValidityFrom , t2.ValidityTo, t2.Flag
from table1 t1
left outer join
( select t22.[Transaction ID], t22.ValidityFrom , t22.ValidityTo, t22.Flag
from table2 t22 join table1 t11 on t11.[Transaction ID] = t22.[Transaction ID]
where
t22.ValidityFrom <= [Transaction Date]
and [Transaction Date] <= t22.ValidityTo
) t2