0

I am trying to update a column in a table where the another column matches and selecting the top 1 for that column as the value to update. Hard to explain, but this is what I wrote:

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

Hopefully that explains what I am trying to do. I have a select statement that might also help:

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
3
  • why don't use MERGE statment Commented Jan 9, 2018 at 9:37
  • I attempted an answer below but note that your use of TOP 1 without an ordering makes no sense. You need to tell us how you want to order things. Commented Jan 9, 2018 at 9:49
  • The order doesn't matter, but I adapted it to work with my table Commented Jan 9, 2018 at 9:54

1 Answer 1

1

We can try doing an update join from CameraSpecifications to a CTE which finds the top GTIN value for each model group. Note carefully that I use an ORDER BY clause in ROW_NUMBER. It makes no sense to use TOP 1 without ORDER BY, so you should at some point update your question and mention TOP 1 with regard to a certain column.

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.