如何基于另一列在一列中累积SQL中的值?

时间:2018-02-05 05:25:58

标签: sql sql-server

我正在尝试根据第二个表中的数量和乘数,在包含不同ItemID的第一个表格中累积结果。我尝试了UPDATE记录和

SET ItemCount = ItemCount + ((SELECT [Multiplier] FROM Table2 WHERE Table1.[ItemID] = Table2.[Item1ID]) * (SELECT [Item1Qty] FROM Table2 WHERE Table1.[ItemID] = Table2.[Item1ID])) + ((SELECT [Multiplier] FROM Table2 WHERE Table1.[ItemID] = Table2.[Item2ID]) * (SELECT [Item2Qty] FROM Table2 WHERE Table1.[ItemID] = Table2.[Item2ID]))

但是失败了,因为SELECT语句返回多个值。获得表3中显示结果的最有效方法是什么

ItemID      ItemCount
10001
10002
10003
10004

Item1ID     Item1Qty        Item2ID     Item2Qty     Multiplier
10001       1               10003        3            4
10004       3               10002        5            2
10003       3               10001        4            3

ItemID      ItemCount
10001       16
10002       10
10003       21
10004       6

3 个答案:

答案 0 :(得分:2)

一种方法是使用union all来计算每件商品的总数量。然后更新table1

with cte as (
    select
        itemID, totalQty = sum(qty)
    from (
        select itemID, qty = item1Qty * Multiplier from table2
        union all select itemID, item2Qty * Multiplier from table2
    ) t
    group by itemID
)

update a
set b.ItemCount = b.qty
from
    table1 a
    join cte b on a.itemID = b.itemID

答案 1 :(得分:1)

这将有效:

Declare @Table as Table (Item1ID varchar(10),Item1Qty int,Item2ID varchar(10),Item2Qty int,Multiplier int)
Insert into @Table Values
('10001',1,'10003',3,4),
('10004',3,'10002',5,2),
('10003',3,'10001',4,3)

Declare @Table1 as Table (Item1ID varchar(10),ItemCount int)
Insert into @Table1 Values
('10001',NULL),
('10002',NULL),
('10003',NULL),
('10004',NULL)

;With T AS
(
Select Item1ID,Item1Qty,Multiplier from @Table
UNION
Select Item2ID,Item2Qty,Multiplier from @Table
)

Update T set T.ItemCount = S.ItemCount from @Table1 T
Inner Join (
Select Item1ID,SUM(Item1Qty*Multiplier) 'ItemCount' from T
Group by Item1ID
) S on S.Item1ID = T.Item1ID

工作sample

答案 2 :(得分:0)

UPDATE T3
SET T3.ItemCount = ISNULL(T3.ItemCount,0) + ((T2.Multiplier * T1.Item1Qty) + (T2.Multiplier * T2.Item2Qty))
FROM Table3 T3
INNER JOIN Table1 AS T1 ON T1.Item1ID = T3.ItemID
INNER JOIN Table2 AS T2 On T2.Item2ID = T1.Item1ID