RiceBucket
RiceBucket

Reputation: 169

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?

Upvotes: 1

Views: 2716

Answers (4)

shajivk
shajivk

Reputation: 570

Try this:

UPDATE Product 
SET COST = COST *
(
    SELECT TOP 1 Multiplier 
    FROM Date_Code 
    WHERE Product.MultiplierCode = Date_Code.Code
    ORDER BY CodeDate DESC
)

Upvotes: 0

Ivan Golović
Ivan Golović

Reputation: 8832

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

Upvotes: 1

aF.
aF.

Reputation: 66697

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.

Upvotes: 0

user330315
user330315

Reputation:

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

Upvotes: 0

Related Questions