我正在尝试创建一个更新查询,它将根据托盘编号匹配更新我的表值。
SELECT [pallet] [quantity]
FROM dba.Inventory
这将返回2列,一列有托盘,另一列有计数。
我需要将它放在一个更新语句中,该语句将匹配此处和表TABLE1之间的每个托盘并更新TABLE1中的计数
答案 0 :(得分:1)
使用公用表表达式。
语法就像
with CTE_Values()
AS
( --- Your Statement---)
Update T
Set Col = C.col
From Table T Join CTE_Values C
On .....
答案 1 :(得分:0)
我认为一个简单的解决方案(不评估看起来很复杂的SELECT
本身)就是将整个SELECT
放入CTE
并将其用作更新的来源。像这样:
;WITH SrcCte AS (
SELECT pallet, SUM(total) as quantity
FROM (
SELECT r1.pallet, total
FROM
(SELECT plet_nbr, COUNT(serl_nbr) as total FROM Inventory group by plet_nbr )c1
right join
(select pallet from dbo.RFS where status NOT LIKE 'Not Available')r1
on r1.pallet = c1.plet_nbr
UNION all
Select r2.pallet, sum(iloc_qty) as total
FROM
(SELECT plet_nbr, iloc_qty FROM Inventory WHERE([matl_nbr] Like '#%')) c2
right join
(select pallet from dbo.RFS where status NOT LIKE 'Not Available') r2
on r2.pallet = c2.plet_nbr
where iloc_qty is not null
GROUP BY r2.pallet
)
AS final
GROUP BY pallet
)
UPDATE Dest
SET Dest.Cnt = Src.Quantity
FROM Table1 AS Dest
JOIN SrcCte AS Src ON Src.pallet = Dest.pallet