SQL:仅在满足条件时,使用同一个表中的值更新字段

时间:2016-05-27 15:26:40

标签: sql sql-server

如何将每个产品的受欢迎程度(仅限销售额> 1)设置为同一表格中最受欢迎产品(来自同一品牌)的受欢迎程度。到目前为止我有这个:

UPDATE Products
SET popularity= 
    (
    SELECT TOP 1 popularity FROM products
    WHERE brand = currentRow.brand
    )
WHERE sales > 1

显然'currentRow'不能存在,因此......

我也在调查this answer,但到目前为止没有运气。

每行iterate/loop会更好,检查条件,并在必要时更新吗?

4 个答案:

答案 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