简体   繁体   中英

SQL query to combine two rows into one as result

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?

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 

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM