SQL Server 2012 更新 table 速率基于 table 2 中的速率

SQL Server 2012 Update table rate based on rate in table 2

我有两个 table,下面是示例

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    

从 Table 2 如果键匹配,那么我们需要从 Table 1 减少 TOTALRATE with RATEREDUCED in Table 2 where BEGINDATE > ENDDATE 它应该发生 直到 table 结束 2 ENDDATE

预期 RESULTS/UPDATE 到 TABLE 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)    

我有很多钥匙 table 两把和 table 一把。 是否可以加入更新

提前致谢

这看起来像是 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;

我不确定使用联接或使用子查询之间的性能差异。也许您可以尝试其他答案中提到的解决方案并将其与(更简单的?)子查询方法进行比较:

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)

与 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