I have a table #vert where I have value column. This data needs to be updated into two channel columns in #hori table based on channel number in #vert table. [code="sql"]CREATE TABLE #Vert (FILTER VARCHAR(3), CHANNEL TINYINT, VALUE TINYINT)INSERT #Vert Values('ABC', 1, 22),('ABC', 2, 32),('BBC', 1, 12),('BBC', 2, 23),('CAB', 1, 33),('CAB', 2, 44) -- COMBINATION OF FILTER AND CHANNEL IS UNIQUECREATE TABLE #Hori (FILTER VARCHAR(3), CHANNEL1 TINYINT, CHANNEL2 TINYINT)INSERT #Hori Values ('ABC', NULL, NULL),('BBC', NULL, NULL),('CAB', NULL, NULL) -- FILTER IS UNIQUE IN #HORI TABLE[/code]One way to achieve this is to write two update statements. After update, the output you see is my desired output[code="sql"]UPDATE HSET CHANNEL1= VALUE FROM #Hori H JOIN #Vert V ON V.FILTER=H.FILTERWHERE V.CHANNEL=1 -- updates only channel1UPDATE HSET CHANNEL2= VALUE FROM #Hori H JOIN #Vert V ON V.FILTER=H.FILTERWHERE V.CHANNEL=2 -- updates only channel2 SELECT * FROM #Hori -- this is desired output[/code]I am not sure if subject makes sense. But my channels number grows in #vert table like 1,2,3,4...and so Channel3, Channel4....so on in #hori table. So I cannot keep writing too many update statements. One other way is to pivot #vert table and do single update into #hori table. I am interested to know if there are other ways to simply update this data.
↧