SQL 合并 2 Select 语句从两行中获取数据

SQL Combine 2 Select Statements to get data from both rows

我有一个 table,每条记录包含 2 行。初始记录和结束时的记录除了第二行的一列具有完整位置外,它们包含相同的信息。

eg 1st row 
Id, New ID, RecordType, Customer Name, Customer Address, Created,   Closed,   location 
1 , Null,   Initial,     John Smith,    1, long lane,   01/05/2019, 10/05/2019, Office
2nd row
Id, New ID, RecordType,  Customer Name, Customer Address, Created, Closed,    Location
2 , 1,     Completed,     John Smith,    1, long lane,   01/05/2019, 10/05/2019, Field

我想报告第一行,但我想要第二行的位置,第二行通过 ID 和新 ID 字段与第一行链接。

我尝试使用 CTE 查询,但返回的结果比仅查询第一行时返回的结果少。

WITH group1 AS (select * from a where closed is not null),
group2 AS (select location from a where closed is not null)
SELECT *
  FROM group1
  JOIN group2 ON group1.ID = group2.NewID ;

我希望这是有道理的,只是想要一些关于如何连接这两行的建议

看来你需要左加入

WITH group1 AS (select * from a where closed is not null),
group2 AS (select location from a where closed is not null)
SELECT group1.*,group2.location
  FROM group1
  left JOIN group2 ON group1.ID = group2.NewID

即使您不需要它,您也可以使用自连接

select t1.*,t2.location
from a t1 left join a t2 on t1.ID = t2.NewID
where t1.closed is not null

您可以使用这可能会有所帮助。

select s1.*, s2.location as newlocation
 FROM tablename as s1
inner join 
 tablename as s2
 on
s1.Id=s2.new_id

你可以加入 table 自身

您需要 table:

的左自联接
select  
  a1.id, a2.newid, a2.recordtype,
  a1.customername, a1.customeraddress,
  a1.created, a1.closed, a2.location
from a a1 left join a a2
on a2.newid = a1.id 
where a1.newid is null

没有 CTE 的正确逻辑是:

select t1.*, t2.location
from a t1 left join
     a t2
     on t2.NewID = t1.ID and
        t2.closed is not null
where t1.closed is not null