带有子查询的更新(WHERE / FROM)

时间:2019-01-14 17:52:59

标签: tsql ms-access sql-update

我正在尝试通过子查询更新名为[资产]的表中的是/否字段(密封)。

子查询结果包含[资产]的ID和要更新的字段的期望结果。

我尝试了一些选项,包括WHERE或FROM子句,但无法达到合适的结果。

下面是基本的Update语句和子查询。任何建议都将不胜感激。

UPDATE [Assets] SET Sealed = IsSealed

SELECT y.Asset AS Asset, 
       IIF(y.TotalSeals>0,Yes,No) AS IsSealed
FROM (
SELECT x.Asset, 
       SUM(IIF(x.BOMTypes="Seal",1,0)) AS BOMSeals, 
       SUM(IIF(x.MatMovTypes="Seal",1,0)) AS MMSeals, 
       SUM(IIF(x.POTypes="Seal",1,0)) AS POSeals, 
       (BOMSeals + MMSeals + POSeals) AS TotalSeals 
FROM (
SELECT [Data - Assets].ID AS Asset, 
       [Data - Inventory].Type AS BOMTypes, 
       NULL AS MatMovTypes, NULL AS POTypes, NULL AS TotalSeals 
FROM [Data - Inventory] INNER JOIN ([Data - Assets] INNER JOIN [Data - BOM] 
ON [Data - Assets].ID = [Data - BOM].Asset) 
ON [Data - Inventory].ID = [Data - BOM].Component 

UNION ALL 
SELECT [Data - Assets].ID AS Asset, NULL AS BOMTypes, 
       [Data - Inventory].Type AS MatMovTypes, 
       NULL AS POTypes, NULL AS TotalSeals 
FROM ([Data - Assets] INNER JOIN [Data - WO] 
ON [Data - Assets].ID = [Data - WO].Asset) 
INNER JOIN ([Data - Inventory] INNER JOIN [Data - MatMov] 
ON [Data - Inventory].ID = [Data - MatMov].Component) 
ON [Data - WO].ID = [Data - MatMov].WorkOrder 

UNION ALL 
SELECT [Data - Assets].ID AS Asset, 
       NULL AS BOMTypes, NULL AS MatMovTypes, 
       [Data - Inventory].Type  AS POTypes, NULL AS TotalSeals 
FROM ([Data - Assets] INNER JOIN [Data - WO] 
ON [Data - Assets].ID = [Data - WO].Asset) 
INNER JOIN ([Data - Inventory] INNER JOIN [Data - PO] 
ON [Data - Inventory].ID = [Data - PO].Component) 
ON [Data - WO].ID = [Data - PO].WorkOrder  
)  AS x 
GROUP BY x.Asset
)  AS y;

1 个答案:

答案 0 :(得分:0)

假设您的表Assets包含一个字段Asset,该字段与您的子查询中的y.Asset列相对应,那么我建议如下:

update assets a inner join
(
    select y.asset, iif(y.totalseals > 0, Yes, No) as issealed
    from 
    (
       ***TLDR
    ) y
) t on a.asset = t.asset 
set a.sealed = t.issealed

这假设您的子查询不包含任何形式的聚合,否则该查询将不可更新。

如果子查询包括聚合,则可以使用域聚合函数,例如DCountDSum(取决于子查询执行的操作)。