如何将每个产品的受欢迎程度(仅限销售额> 1)设置为同一表格中最受欢迎产品(来自同一品牌)的受欢迎程度。到目前为止我有这个:
UPDATE Products
SET popularity=
(
SELECT TOP 1 popularity FROM products
WHERE brand = currentRow.brand
)
WHERE sales > 1
显然'currentRow'不能存在,因此......
我也在调查this answer,但到目前为止没有运气。
每行iterate/loop会更好,检查条件,并在必要时更新吗?
答案 0 :(得分:3)
您需要的是别名:
UPDATE Tgt
SET popularity = (
SELECT Max(popularity)
FROM products Ref
WHERE Ref.brand = Tgt.brand --< Refer by alias
)
FROM Products Tgt --< Give the target table an alias
WHERE sales > 1
答案 1 :(得分:0)
试试这个脚本:
SELECT TOP 1 POPULARITY, BRAND
INTO #TEMP
FROM PRODUCTS
WHERE SALES > 1
UPDATE PRODUCTS
SET POPULARITY = B.POPULARITY
FROM PRODUCTS A, #TEMP B
WHERE A.BRAND = B.BRAND
答案 2 :(得分:0)
您可以使用JOIN
和派生表
UPDATE P1
SET P1.Popularity = P2.Popularity
FROM Products P1
INNER JOIN (SELECT MAX(Popularity) as [Popularity], Brand
FROM Products P2
GROUP BY Brand) P2 on P2.Brand = P1.Brand
WHERE SALES > 1
答案 3 :(得分:0)
如果你使用“TOP”,你需要使用ORDER BY,否则无法保证它会给你最受欢迎。如果您还在寻找最受欢迎的,只有销售额大于1的地方,您的子查询中需要一个WHERE语句。使用别名为@ Y.B。建议,你可以这样做(在子查询中有或没有WHERE)。
UPDATE a
SET popularity=
(
SELECT TOP 1 b.popularity FROM Products b
WHERE b.brand = a.brand
AND sales > 1
ORDER BY b.popularity DESC
)
FROM Products a
WHERE sales > 1