I am bit in a struggle with a select query on one table but join 2 same columns together. To simplify my problem, I made a reconstruction of the situation. I got a table that looks like this:
declare @DummyTable Table
(
Id int,
MainName varchar(20),
SubName varchar(20),
sequenceNumber int
)
This table contains the next data:
insert into @DummyTable
values ( 0, 'MainName1', 'SubName1', 1),
( 1, 'MainName1', 'SubName2', 2),
( 2, 'MainName1', 'SubName3', 3),
( 3, 'MainName1', 'SubName6', 4),
( 4, 'MainName1', 'SubName7', 5),
( 5, 'MainName2', 'SubName1', 1),
( 6, 'MainName2', 'SubName2', 2),
( 7, 'MainName2', 'SubName3', 3),
( 8, 'MainName2', 'SubName4', 4),
( 9, 'MainName2', 'SubName5', 5),
(10, 'MainName2', 'SubName6', 6),
(11, 'MainName2', 'SubName7', 7),
(12, 'MainName3', 'SubName1', 1),
(13, 'MainName3', 'SubName2', 2),
(14, 'MainName3', 'SubName3', 3)
Now I try to get all the records containing the text MainName1 and on the same row I want also the records MainName2, matching by the SubName column, like this:
Id | MainName | SubName | s | Id | MainName | SubName | s -- s = SequenceNumber
--------------------------------------------------------------
5 | MainName2 | SubName1 | 1 | 0 | MainName1 | SubName1 | 1
6 | MainName2 | SubName2 | 2 | 1 | MainName1 | SubName2 | 2
7 | MainName2 | SubName3 | 3 | 2 | MainName1 | SubName3 | 3
8 | MainName2 | SubName4 | 4 | NULL | NULL | NULL | NULL
9 | MainName2 | SubName5 | 5 | NULL | NULL | NULL | NULL
10 | MainName2 | SubName6 | 6 | 3 | MainName1 | SubName6 | 4
11 | MainName2 | SubName7 | 7 | 4 | MainName1 | SubName7 | 5
I try to manage this with the next query:
select *
from @DummyTable dt1
left join @DummyTable dt2 on dt1.SubName = dt2.SubName
where dt1.MainName like '%Name2%'
and dt2.MainName like '%Name1%'
order by dt1.MainName, dt1.sequenceNumber
But when I execute this query, I get the result I want but with records with the ids 8 and 9 missing. I tried to right join, or only join (without left or right) but all gives the same result, not showing records with the ids 8 and 9. I cannot figure out what I am doing wrong here and I am also wondering why I am not seeing the missing records. Could anyone help me to understand my problem and how I can fix it?