[英]T-SQL to loop through records in one table and modify field value based on another table
I have 2 tables. 我有2张桌子。
TableA
has a series of products with costs and TableB
has a series of multipliers based on dates. TableA
有一系列的产品,成本和TableB
有一系列基于日期乘数。 For example: 例如:
TableA (Key: Product) TableA (键:产品)
Product ID Cost Multiplier Code
ProductA 100 ABC
ProductB 200 DEF
ProductC 300 ABC
ProductD 400 JKL
TableB (Key: Date, Code) TableB (键:日期,代码)
Date Code Multiplier
01/01/12 ABC 100
01/01/12 DEF 200
01/01/12 GHI 300
01/01/12 JKL 400
16/03/12 ABC 300
20/06/12 ABC 900
15/05/12 DEF 700
Desired results: 所需结果:
TableA (Key: Product) TableA (键:产品)
Product ID Cost Multiplier Code
ProductA 90000 ABC
ProductB 140000 DEF
ProductC 270000 ABC
ProductD 160000 JKL
What I would like to do is write a T-SQL script which loops through ALL of TableA
and at the same time, multiply up the Cost
column using TableB
multipliers. 我想这样做的是写一个通过所有的循环一个T-SQL脚本
TableA
,并在同一时间, 乘了 Cost
使用列TableB
乘数。 So in the example of ProductA above, Cost
should become 100 x 900 = 90,000
. 因此,在上面的ProductA示例中,
Cost
应变为 100 x 900 = 90,000
。
It needs to use the latest modifier based on the date in TableB
hence using 900 as the modifier. 它需要基于
TableB
的日期使用最新的修饰符,因此使用900作为修饰符。
Is this possible? 这可能吗?
Try: 尝试:
UPDATE a
SET Cost *= _b.Multiplier
FROM a
JOIN (
SELECT Code,
Multiplier,
ROW_NUMBER() OVER (PARTITION BY Code ORDER BY Date DESC) RowNum
FROM b
) _b ON _b.Code = a.Code AND _b.RowNum = 1
select p.productid,
p.cost * m.multiplier,
p.multiplier_code
from tableA p
join (
select b1.multiplier, b1.code
from tableB b1
where b1.date = (select max(b2.date)
from tableB b2
where b2.code = b1.code)
) m on p.multiplier_code = m.code
update TableA
set a.Cost = a.Cost * aux2.Multiplier
from TableA a
inner join
(select b.Code, b.Multiplier from TableB b
inner join
(select max(Date) as 'Date', Code
from TableB
group by Code) aux on b.Date = aux.Date and b.Code = aux.Code
) aux2 on aux2.Code = a.MultiplierCode
aux
gets the max Date for a given Code. aux
获取给定代码的最大日期。 aux2
gets the multiplier for the dates in aux
. aux2
获得aux
日期的乘数。
Try this: 尝试这个:
UPDATE Product
SET COST = COST *
(
SELECT TOP 1 Multiplier
FROM Date_Code
WHERE Product.MultiplierCode = Date_Code.Code
ORDER BY CodeDate DESC
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.