Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

Updating records using self join or row number function

$
0
0
IF OBJECT_ID('tempdb..#Temp') IS NOT NULL DROP TABLE #Temp
GO

CREATE TABLE #Temp
(
	  ID INT
	, CYear INT
	, Val INT
	, Descrp Varchar(10) NULL
	, Cd INT
	, ToBeUpdated Varchar(5) NULL
)

INSERT INTO #Temp
(
	  ID
	, CYear
	, Val
	, Descrp
	, Cd
	, ToBeUpdated
)

SELECT 2014, 2013, 111, 'ABC', 2, NULL
UNION
SELECT 2014, 2014, 111, 'XYZ', 2, NULL
UNION
SELECT 2014, 2014, 222, 'TTT', 3, NULL
UNION
SELECT 2014, 2013, 333, 'ZZZ', 4, NULL
UNION
SELECT 2014, 2014, 333, 'VVV', 5, NULL

SELECT * FROM #Temp
ORDER BY Val, CYear

All, I have the above #table. You'll notice that there are duplicate values in "Cd" column i.e. "Cd=2".

If the values in ID, Val and Cd are same then, I want to update the "CodeFlag" column for those records with "Descrp" column of the recent CYear. So, my "ToBeUpdated" column would have a value of "XYZ" for both the records where Cd=2 (Since, XYZ is the Descrp for CYear 2014(the latest one))

Also, if the values in ID and Val column are same but values in "Cd" is different, then ToBeUpdated = Descrp of that particular record. In my case the "ToBeUpdated" value for Cd=4 would be "ZZZ" and for Cd=5, it would be "VVV" since the ID and Val column values are same for those records. Let me know if you have any questions.


Viewing all articles
Browse latest Browse all 23857

Trending Articles