我正在尝试更新另一列匹配的表中的列,并选择该列的前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
答案 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;