I have some record as under for tblFiltered
ID RowID Position Data
1 1 a1 R
1 1 b1 N
1 1 e1 K
1 1 g1 N
1 1 h1 R
1 2 b2 T
1 2 c2 B
1 2 d2 Y
1 2 f2 F
And the table tblComplete has the below data
RowID Position Data
1 a1 NULL
1 b1 NULL
1 c1 NULL
1 d1 NULL
1 e1 NULL
1 f1 NULL
1 g1 NULL
1 h1 NULL
2 a2 NULL
2 b2 NULL
2 c2 NULL
2 d2 NULL
2 e2 NULL
2 f2 NULL
2 g2 NULL
2 h2 NULL
The desired output is
ID RowID Position CompleteData
1 1 a1 R
1 1 b1 N
1 1 c1 NULL
1 1 d1 NULL
1 1 e1 K
1 1 f1 NULL
1 1 g1 N
1 1 h1 R
1 2 a2 NULL
1 2 b2 T
1 2 c2 B
1 2 d2 Y
1 2 e2 NULL
1 2 f2 F
1 2 g2 NULL
1 2 h2 NULL
That means the records that are not in tblFiltered will be taken from tblCompelete and it will be filled.
e.g. c1, d1 and f1 are not in tblFiltered and henceforth are taken from tblCompelte and being added to the resultant output.
I have written the query
select t.ID,c.RowID,c.Position,
CompleteData = case when t.Data IS null then null else t.data end
from @CompleteData c
left join @tblFiltered t
on c.Position = t.Position
whose output is
ID RowID Position CompleteData
1 1 a1 R
1 1 b1 N
NULL 1 c1 NULL
NULL 1 d1 NULL
1 1 e1 K
NULL 1 f1 NULL
1 1 g1 N
1 1 h1 R
NULL 2 a2 NULL
1 2 b2 T
1 2 c2 B
1 2 d2 Y
NULL 2 e2 NULL
1 2 f2 F
NULL 2 g2 NULL
NULL 2 h2 NULL
As can be seen, I am unable to set the ID. Also, if the ID’s become > 1 in tblFiltered, then how will I keep track of that?
DDL are
Declare @tblFiltered table(ID int,RowID int,Position varchar(10),Data varchar(10))
Insert into @tblFiltered
Select 1,1,'a1','R' union all
Select 1,1,'b1','N' union all
Select 1,1,'e1','K' union all
Select 1,1,'g1','N' union all
Select 1,1,'h1','R' union all
Select 1,2,'b2','T' union all
Select 1,2,'c2','B' union all
Select 1,2,'d2','Y' union all
Select 1,2,'f2','F'
Declare @CompleteData table (RowID int,Position varchar(10),Data varchar(10))
Insert into @CompleteData
select 1, 'a1', Null Union All
select 1, 'b1', Null Union All
select 1, 'c1', Null Union All
select 1, 'd1', Null Union All
select 1, 'e1', Null Union All
select 1, 'f1', Null Union All
select 1, 'g1', Null Union All
select 1, 'h1', Null Union All
select 2, 'a2', Null Union All
select 2, 'b2', Null Union All
select 2, 'c2', Null Union All
select 2, 'd2', Null Union All
select 2, 'e2', Null Union All
select 2, 'f2', Null Union All
select 2, 'g2', Null Union All
select 2, 'h2', Null
--Select * from @tblFiltered
--Select * from @CompleteData
Thanks in advance
1 Answer