简体   繁体   中英

T-SQL to loop through records in one table and modify field value based on another table

I have 2 tables. TableA has a series of products with costs and TableB has a series of multipliers based on dates. For example:

TableA (Key: Product)

Product ID     Cost   Multiplier Code
ProductA       100    ABC
ProductB       200    DEF
ProductC       300    ABC
ProductD       400    JKL

TableB (Key: Date, Code)

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)

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. So in the example of ProductA above, Cost should become 100 x 900 = 90,000 .

It needs to use the latest modifier based on the date in TableB hence using 900 as the modifier.

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. aux2 gets the multiplier for the dates in 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
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM