Wednesday, February 22, 2017

How to Update a Table by Joining with another Map Table using Sub Query in SQL Server

T-SQL Sub Query  to update a Table by Joining with another map Table in SQL Server
USE [TAMATAM]
GO
UPDATE  [TBL_Trans]
SET Week_Num= WK_Number
FROM
(
SELECT DISTINCT 'W'+CONVERT(VARCHAR,C.WK_Num) WK_Number,T.Week_Id  FROM            [TBL_Trans] T  JOIN   [TBL_Calendar] C
ON T.Week_Id=C.WK_Id AND C.[FY_QTR] =T.[QTR]
       ) S1
WHERE  [TBL_Trans].Week_Id=S1.Week_Id

Example :
Lets suppose we have a Table called   [TBL_Trans] as follows , where we want to update the 'Week_Num' by mapping with another table called [TBL_Calendar] 

SELECT*FROM [TBL_Trans];


SELECT*FROM [TBL_Calendar];


Now we can update the [Week_Num] column of  [TBL_Trans] by Joining with the map table [TBL_Calendar] :based on the key Column 'Week_Id' as follows :

UPDATE  [TBL_Trans]
SET Week_Num= WK_Number
FROM
(
SELECT DISTINCT 'W'+CONVERT(VARCHAR,C.WK_Num) WK_Number,T.Week_Id  FROM            [TBL_Trans] T  JOIN   [TBL_Calendar] C
ON T.Week_Id=C.WK_Id AND C.[FY_QTR] =T.[QTR]
       ) S1
WHERE  [TBL_Trans].Week_Id=S1.Week_Id

Ouput :

-------------------------------------------------------------------------------------------------------- 
Thanks, TAMATAM ; Business Intelligence & Analytics Professional 
--------------------------------------------------------------------------------------------------------

No comments:

Post a Comment

Hi User, Thank You for visiting My Blog. Please post your genuine Feedback or comments only related to this Blog Posts. Please do not post any Spam comments or Advertising kind of comments which will be Ignored.

Featured Post from this Blog

How to compare Current Snapshot Data with Previous Snapshot in Power BI

How to Dynamically compare two Snapshots Data in Power BI Scenario: Suppose, we have a sample Sales data, which is stored with Monthly Snaps...

Popular Posts from this Blog