我有两个表,下面是示例
Table1
KEY BEGIN_DATE TOTAL_RATE
1 1974-01-01 3
1 1981-01-01 3
1 1983-01-01 4
1 1985-07-01 4
1 1989-10-01 7
1 1990-07-01 10
1 1997-10-01 11
1 2008-04-01 13
TABLE2
KEY END_DATE RATE_REDUCED
1 1989-09-30 2
1 1997-09-31 4
如果密钥匹配,则从表2中我们需要从表1中减少TOTALRATE 表2中的RATEREDUCED,其中BEGINDATE>结束,它应该发生 直到表2结束
预期结果/更新至表1:
结果
KEY BEGIN_DATE NEW_RATE
1 1974-01-01 3
1 1981-01-01 3
1 1983-01-01 4
1 1985-07-01 4
1 1989-10-01 7 - 2 = 5 (Date is Greater than 1989-09-30)
1 1990-07-01 10 - 2 = 8 (Date is Greater than 1989-09-30)
1 1997-10-01 11 - 2 - 4 = 5 (Date is Greater than two dates)
1 2008-04-01 13 - 2 - 4 = 7 (Date is Greater than two dates)
我在表二和表一中有很多键。 是否可以加入
提前致谢
答案 0 :(得分:2)
这似乎是outer apply
:
select t1.*,
(t1.total_rate - coalesce(t2.rate_reduced, 0)) as total_rate
from table1 t1 outer apply
(select sum(t2.rate_reduced) as rate_reduced
from table2 t2
where t1.begin_date > t2.end_date and
t1.key = t2.key
) t2;
编辑:
如果您想将其转换为update
,那很简单:
update t1
set total_rate = (t1.total_rate - coalesce(t2.rate_reduced, 0))
from table1 t1 outer apply
(select sum(t2.rate_reduced) as rate_reduced
from table2 t2
where t1.begin_date > t2.end_date and
t1.key = t2.key
) t2;
答案 1 :(得分:2)
与Gordon相似,我们在这里使用CROSS APPLY中的Update。此方法仅更新符合条件的记录
Update Table1 Set TOTAL_RATE=TOTAL_Rate-B.Adj
From Table1 A
Cross Apply (
Select Adj=sum(RATE_REDUCED)
From Table2
Where END_DATE<=A.BEGIN_DATE and [Key]=A.[Key]
) B
Where B.Adj is not NULL
更新后的表1现在看起来像这样
KEY BEGIN_DATE TOTAL_RATE
1 1974-01-01 3
1 1981-01-01 3
1 1983-01-01 4
1 1985-07-01 4
1 1989-10-01 5
1 1990-07-01 8
1 1997-10-01 5
1 2008-04-01 7
答案 2 :(得分:0)
我不确定使用连接或使用子查询之间的性能差异。也许您可以尝试其他答案中提到的解决方案,并将其与(更简单的?)子查询方法进行比较:
update table1
set total_rate = total_rate -
(select COALESCE(sum(new_rate),0)
from table2
where begin_date > end_date
and table1.key = table2.key)