我正在尝试将列总数(Totl)更新为SUM(卷)除以COUNT(*),仅针对列/ s的组(周)中的行,在4个不同的表中水果(Fruit_Volume)和许多记录(有更多属性,如买家,种植区域..),我只想生成有机(Fruit_Type)的Apples(Item_Name)值,按周(日期)分组。 -TIA
UPDATE Fruit_Volume
SET Totl = B.Totl
FROM (SELECT SUM(Volume)/COUNT(*) Totl FROM Fruit_Volume
WHERE Item_Name LIKE 'Apple%' AND Fruit_Type = 'Organic'
GROUP BY Week -- I feel the need to group by Item_Group, Fruit_Type
) as B
WHERE Item_Name LIKE 'Apple%' AND Fruit_Type = 'Organic'
答案 0 :(得分:0)
我假设你想在同一周内为同一产品记录多行的共同行,然后将其应用于受本周影响的水果。
UPDATE fv
SET fv.Totl = B.Totl
FROM
Fruit_Volume fv
INNER JOIN
(
SELECT
SUM(Volume) / COUNT(*) Totl,
[Week]
FROM
Fruit_Volume
WHERE
Item_Name LIKE 'Apple%' AND Fruit_Type = 'Organic'
GROUP BY
[Week]
) as B
ON fv.[Week] = b.[Week]
WHERE
Item_Name LIKE 'Apple%' AND Fruit_Type = 'Organic';
修改强>
通过CTE进行更新,查询可以DRY'd
一点。
WITH cte AS
(
SELECT
*
FROM
Fruit_Volume
WHERE
Item_Name LIKE 'Apple%' AND Fruit_Type = 'Organic'
)
UPDATE cte
SET cte.Totl = B.Totl
FROM
cte
INNER JOIN
(
SELECT
SUM(Volume) / COUNT(*) Totl,
[Week]
FROM
cte
GROUP BY
[Week]
) as B
ON cte.[Week] = b.[Week];