Reputation: 4999
I have one requirement to write an SQL Server query to read from one table, let's assume the table is called Table1, the structure and rows look like this:
The key is if the column RefID has value, for example, row 2 has RefID value 3, it refers to another row's ID (row 3), and row 3 must also have a not-null RefID and the value must be the ID of the first one. The idea is these two belong to the same object so I would like to get them as one result row.
I know I can do inner join on the same table like this:
select T1.*, T2.* from Table1 T1 inner join Table1 T2 on T1.RefID = T2.ID
where T1.ID is not null
But the thing is the result has redundancy: the result would have 4 rows and as I mentioned, since row 2 and row 3 together represent one object, I would like to only get 2 rows: one for row 2 row 3, and the other for row 4 row 5. How can I do that?
Upvotes: 1
Views: 1626
Reputation: 63
if the records are redundant and ID column is unique i am totaly aggree with @bulat you dont need to where clause they are already eliminated. i thing this query will works for you.
select * from Table1 a inner join Table1 b ON a.ID=b.RefID and a.ID>b.ID
Upvotes: 1
Reputation: 6969
Just make sure that their IDs are ordered in a row:
select T1.*, T2.* from Table1 T1 inner join Table1 T2 on T1.RefID = T2.ID AND T1.ID < T2.ID
where T1.ID is not null
Upvotes: 1