我有两张桌子。
表A: A、B、C栏为产品
ID SDate A B C PercentageVal
---------------------------------------------------------
1 02/22/2021 3.04 0.43 7.15 ??
2 04/13/2021 12.12 5.32 0.22 ??
3 06/07/2021 1.01 1.11 8.02 ??
4 03/01/2021 2.09 4.09 9.02 ??表B:
ID TableAID Product StartDate EndDate PValue
---------------------------------------------------------
1 1 A 01/01/2021 06/30/2021 10
2 2 B 03/01/2021 05/31/2021 12
3 3 C 02/01/2021 06/30/2021 10要计算表A中的PercentageVal,需要使用以下逻辑。
步骤1:为表A中的产品列A、B和C获取PercentValue
select B.Product, B.PValue
into #temp
from A
join B on A.SDate between B.StartDate and B.EndDate;步骤2:在这里生成动态查询来计算表A的PercentageVal
Select 'Update A set PercentageVal= '+ string_agg(Product * (PValue/100)) + ' Where ID='+ B.TableAID
From B;表A大约有100万行。执行这个更新语句需要花费20分钟的时间。
有什么更好的方法来更新表A吗?
预期结果
在TableA Row1中,SDate是2月,因此只有产品A和C才有资格计算。由于产品B的开始日期和结束日期在TableB中不匹配。所以我需要
(A*(10/100) + C*(10/100)) => (3.04*(10/100) + 7.15*(10/100)) => 1.019同样,对于Row2,所有三种乘积都可以作为计算,因为SDate满足这个条件。
(A*(10/100) + B*(12/100) + C*(10/100)) => (12.12*0.10)+(5.32*0.12)+(0.22*0.10) => 1.872请注意,用于计算的产品是动态的,基于SDate的产品应该介于StartDate和TableB中的EndDate之间。
发布于 2021-08-03 17:50:25
您可以使用多个apply
update a
set percentageval = b.cal
from a outer apply
(select sum(v.val * b.pvalue / 100) as calc
from b cross apply
(values ('A', a.a), ('B', a.b), ('C', a.c)
) v(product, val)
where a.sdate between b.startdate and b.enddate and
a.id = b.tableaid and
v.product = b.product
) b;https://stackoverflow.com/questions/68640618
复制相似问题