使用select语句

时间:2018-01-09 09:36:28

标签: sql-server

我正在尝试更新另一列匹配的表中的列,并选择该列的前1作为要更新的值。 很难解释,但这就是我写的:

UPDATE CameraSpecifications AS a
SET a.Variant = (
SELECT TOP 1 GTIN
FROM CameraSpecifcations 
WHERE b.ModelGroup = a.ModelGroup )

希望这能解释我的目标。 我有一个可能也有帮助的select语句:

SELECT 
    (
        SELECT TOP 1 b.GTIN
        FROM CameraSpecifications AS b
        WHERE b.ModelGroup = a.ModelGroup
    ) AS Gtin,
    a.ModelGroup, 
    COUNT(a.ModelGroup)
FROM CameraSpecifications AS a
GROUP BY a.ModelGroup

1 个答案:

答案 0 :(得分:1)

我们可以尝试从CameraSpecifications到CTE进行更新加入,CTE会为每个模型组找到最高GTIN值。请注意,我在ORDER BY中使用ROW_NUMBER子句。没有TOP 1使用ORDER BY是没有意义的,因此您应该在某个时候更新您的问题并在某个专栏中提及TOP 1

WITH cte AS (
    SELECT ModelGroup, GTIN,
        ROW_NUMBER() OVER (PARTITION BY ModelGroup ORDER BY some_col) rn
    FROM CameraSpecifications
)

UPDATE cs
SET Variant = t.GTIN
FROM CameraSpecifcations cs
INNER JOIN cte t
    ON cs.ModelGroup = t.ModelGroup
WHERE
    t.rn = 1;