I need help to get the solution for this condition. I have a table containing records, there is a field sku, in this record i have sku’s appearing multiple times. Table structure is like this rid|id|sku|name
if any sku is available on table multiple times the record looks like this
rid id sku name
--- -- ------ --------------
1 3 rs-123 test product
2 3 rs-123 test product
3 4 rs-125 test product 2
4 4 rs-125 test product 2
5 4 rs-125 test product 2
6 6 rs-126 test product 3
What I need is to update the table with duplicate records keeping first record unchanged (N-1). So for example I need to run SQL statement which update only duplicate records, so if first record is updated it will look like this
rid id sku name
--- -- ------ --------------
1 3 rs-123 test product
2 3 updated updated
I was trying to achieve something with this SQL statement but it is not working
WITH duplicates AS (
SELECT
ROW_NUMBER() OVER (PARTITION BY id ORDER BY rid) AS duplicate_id,
*
FROM
test
)
UPDATE
duplicates
SET
sku = updated
WHERE
duplicate_id > 1
Any advise would be highly appreciated.
Perhaps you may give it a try with a variable:
SQLFIDDLE DEMO
For updating:
SQLFIDDLE DEMO for UPDATING
Here is another using
Joins:http://sqlfiddle.com/#!2/ddf47/2
To update both sku and name:
http://sqlfiddle.com/#!2/97f4f/1
LOOKING AT OP’S QUESTION having used ROW_NUMBER() IN SQL SERVER
http://sqlfiddle.com/#!3/355c4/2