SQL Combine 2 Select语句从两行获取数据

时间:2019-07-11 09:56:14

标签: sql common-table-expression sql-server-2017

我有一个表,每个记录包含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 ;

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

4 个答案:

答案 0 :(得分:0)

似乎您需要左加入

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

即使您不需要cte,也可以使用selft join

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

答案 1 :(得分:0)

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

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

您可以将表自身连接

答案 2 :(得分:0)

您需要表的左自连接:

 let imageURL = UIImage(named: "TestImage")?.getURL()

 let attachment = try! UNNotificationAttachment(identifier: "image", url: imageURL!, options: [:])
    content.attachments = [attachment]

答案 3 :(得分:0)

没有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