Reputation: 3
My issue is pretty straight forward, all of the queries we have tried error out. I am a novice user and am still learning the SQL language, any help would be very appreciated.
I'm attempting to update a table to where if the rate column matches Mat ID
will update with the first value from that grouping.
+------+--------+
| Rate | Mat ID |
+------+--------+
| 1 | 81 |
| 2 | 82 |
| 2 | 83 |
| 3 | 85 |
| 2 | 86 |
| 2 | 87 |
| 3 | 88 |
+------+--------+
Expected result:
+------+--------+
| Rate | Mat ID |
+------+--------+
| 1 | 81 |
| 2 | 82 |
| 2 | 82 |
| 3 | 85 |
| 2 | 82 |
| 2 | 82 |
| 3 | 85 |
+------+--------+
Upvotes: 0
Views: 32
Reputation: 8991
Assuming the following:
85
and not 88
.The following UPDATE
statement meets your requirements:
;
WITH CTE_MinMatID
AS (
SELECT Rate,
MIN(MatID) MinMatID
FROM @table
GROUP BY Rate
)
UPDATE t
SET t.MatID = cte.MinMatID
FROM @table AS t
INNER JOIN CTE_MinMatID cte ON cte.Rate = t.Rate;
Upvotes: 1