Hi Richa,
Refer below query.
SQL
DECLARE @Table1 AS TABLE
(
Id INT,
Ute_Nm INT,
Ute_Name NVARCHAR(25),
Ein_Nm INT,
DeletedFlag INT,
[DateTime] DateTime
)
INSERT INTO @Table1(Id, Ute_Nm, Ute_Name, Ein_Nm, DeletedFlag)VALUES(6872,500001,'AA',01025,0)
INSERT INTO @Table1(Id, Ute_Nm, Ute_Name, Ein_Nm, DeletedFlag)VALUES(6349,500002,'BB',01026,0)
INSERT INTO @Table1(Id, Ute_Nm, Ute_Name, Ein_Nm, DeletedFlag)VALUES(6616,500003,'CC',01028,0)
INSERT INTO @Table1(Id, Ute_Nm, Ute_Name, Ein_Nm, DeletedFlag)VALUES(6873,500004,'DD',01032,0)
INSERT INTO @Table1(Id, Ute_Nm, Ute_Name, Ein_Nm, DeletedFlag)VALUES(6271,500005,'EE',00104,0)
DECLARE @Table2 AS TABLE
(
Id INt,
Grn_Nm INT,
Grn_Name NVARCHAR(25),
Ein_Nm INT,
DeletedFlag INT,
MK1 INT,
MK2 INT,
MK3 INT,
[DateTime] DateTime
)
INSERT INTO @Table2 (Id,Grn_Nm,Grn_Name,Ein_Nm,DeletedFlag,MK1,MK2,MK3) VALUES(35251,1317,'A',01025,0,17,1,0)
INSERT INTO @Table2 (Id,Grn_Nm,Grn_Name,Ein_Nm,DeletedFlag,MK1,MK2,MK3) VALUES(35252,1318,'B',01026,0,5402,61,1)
INSERT INTO @Table2 (Id,Grn_Nm,Grn_Name,Ein_Nm,DeletedFlag,MK1,MK2,MK3) VALUES(36599,9088,'C',01026,0,23,3,12)
INSERT INTO @Table2 (Id,Grn_Nm,Grn_Name,Ein_Nm,DeletedFlag,MK1,MK2,MK3) VALUES(36604,9098,'D',03455,0,457,8,0)
INSERT INTO @Table2 (Id,Grn_Nm,Grn_Name,Ein_Nm,DeletedFlag,MK1,MK2,MK3) VALUES(34546,12817,'E',01028,0,1145,780,0432)
INSERT INTO @Table2 (Id,Grn_Nm,Grn_Name,Ein_Nm,DeletedFlag,MK1,MK2,MK3) VALUES(38988,14083,'F',01028,0,17,34,6286)
INSERT INTO @Table2 (Id,Grn_Nm,Grn_Name,Ein_Nm,DeletedFlag,MK1,MK2,MK3) VALUES(33232,9025,'G',01032,0,17,2356,45)
INSERT INTO @Table2 (Id,Grn_Nm,Grn_Name,Ein_Nm,DeletedFlag,MK1,MK2,MK3) VALUES(34346,165,'H',00104,0,17,33435,2)
DECLARE @Table3 AS TABLE
(
Ute_Nm INT,
Grn_Nm INT,
DeletedFlag INT
)
INSERT INTO @Table3(Ute_Nm, Grn_Nm) VALUES(500001, 1317)
INSERT INTO @Table3(Ute_Nm, Grn_Nm) VALUES(500002, 1318)
INSERT INTO @Table3(Ute_Nm, Grn_Nm) VALUES(500002, 9088)
INSERT INTO @Table3(Ute_Nm, Grn_Nm) VALUES(500002, 9098)
INSERT INTO @Table3(Ute_Nm, Grn_Nm) VALUES(500003, 12817)
INSERT INTO @Table3(Ute_Nm, Grn_Nm) VALUES(500003, 14083)
INSERT INTO @Table3(Ute_Nm, Grn_Nm) VALUES(500004, 9025)
INSERT INTO @Table3(Ute_Nm, Grn_Nm) VALUES(500005, 165)
SELECT u.*, g.MK1, g.MK2, g.MK3
FROM @Table3 as gu
JOIN @Table1 as u ON u.Ute_Nm = gu.Ute_Nm
JOIN @table2 as g ON gu.Grn_Nm = g.Grn_Nm
Output
Id |
Ute_Nm |
Ute_Name |
Ein_Nm |
DeletedFlag |
DateTime |
MK1 |
MK2 |
MK3 |
6872 |
500001 |
AA |
1025 |
0 |
NULL |
17 |
1 |
0 |
6349 |
500002 |
BB |
1026 |
0 |
NULL |
5402 |
61 |
1 |
6349 |
500002 |
BB |
1026 |
0 |
NULL |
23 |
3 |
12 |
6349 |
500002 |
BB |
1026 |
0 |
NULL |
457 |
8 |
0 |
6616 |
500003 |
CC |
1028 |
0 |
NULL |
1145 |
780 |
432 |
6616 |
500003 |
CC |
1028 |
0 |
NULL |
17 |
34 |
6286 |
6873 |
500004 |
DD |
1032 |
0 |
NULL |
17 |
2356 |
45 |
6271 |
500005 |
EE |
104 |
0 |
NULL |
17 |
33435 |
2 |