1

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?

4

4 回答 4

1

尝试:

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
于 2012-06-20T10:07:49.397 回答
0

尝试这个:

UPDATE Product 
SET COST = COST *
(
    SELECT TOP 1 Multiplier 
    FROM Date_Code 
    WHERE Product.MultiplierCode = Date_Code.Code
    ORDER BY CodeDate DESC
)
于 2012-06-20T10:21:26.690 回答
0
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获取给定代码的最大日期。 aux2获取 中日期的乘数aux

于 2012-06-20T10:01:56.507 回答
0
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
于 2012-06-20T09:58:47.560 回答