我有以下2表:
Col1|Col2|Col3
Val1 T1
Val2 T2
Col1|Col2|Col3|Col4
Val1 test 1
Val1 test 2
Val1 T1 3
Val2 test 1
Val2 T2 2
我需要更新值Col3
的Table 1
符合表2的COL3的总和,直到表的col2的2到达从col2的值表1.所以,表1应该是这样的:
Col1|Col2|Col3
Val1 T1 6
Val2 T2 3
因此,它总计1+2+3 = 6
为T1和1+2 = 3
T2。
基本上,两个表的Col1都是关键。我正在使用MSSQL2008
服务器。我曾尝试用Cursor做到这一点,但到目前为止还没有运气。请注意,表2中的按列排序是日期列(Column4)。它由Desc排序。
这有点棘手。您可以使用相关的子查询获取截止点:
update t1
set col3 = t2.sum_col3
from t1 join
(select t2.col1, sum(t2.col3) as sum_col3
from t2
where t2.t4 >= (select tt2.t4
from t2 tt2 join
t1 tt1
on tt2.col1 = tt1.col1 and
tt2.col2 = tt1.col2
)
group by t2.col1
) t2
on t2.col1 = t1.col1;
或者,您可以使用窗口函数(但不能使用累积和):
update t1
set col3 = t2.sum_col3
from t1 join
(select t2.col1,
sum(t2.col3) as sum_col3
from (select t2.col1,
min(case when tt2.col1 = tt1.col2 then tt2.col4 end) over (partition by tt2.col1) as col4_match
from t2 tt2 join
t1 tt1
on tt2.col1 = tt1.col1
) t2
where col4 >= col4_match
group by t2.col1
) t2
on t2.col1 = t1.col1
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句