简体   繁体   English

SQL查询将两行合并为结果

[英]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: 我有一个要求编写一个SQL Server查询以从一个表中读取数据的要求,假设该表名为Table1,其结构和行如下所示:

在此处输入图片说明

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. 关键在于列RefID是否具有值,例如,第2行的RefID值为3,它引用另一行的ID(第3行),并且第3行也必须具有非空的RefID,并且值必须是第一个。 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? 但是问题是结果具有冗余性:结果将有4行,并且正如我提到的那样,由于第2行和第3行一起代表一个对象,所以我只希望获得2行:一个代表第2行第3行,另一个代表第2行对于第4行第5行。我该怎么做?

Just make sure that their IDs are ordered in a row: 只需确保其ID连续排列即可:

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. 如果记录是多余的,并且ID列是唯一的,我完全同意@bulat,那么您不需要在where子句中将它们消除。 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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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