如何在查询中合并两个表?

时间:2019-07-16 11:14:39

标签: sql sql-server

我的数据库中有两个表,一个用于离开飞机,另一个用于到达飞机。它们每个都包括一列,其中包含跑道标志。现在我要进行查询,将两个表合并在一起,计算有多少架飞机到达跑道,还有多少架飞机离开跑道。

这是我的尝试:

SELECT runway_sign as Landebahn, [Anzahl gelandet], [Anzahl gestartet]  from
    (
        SELECT runway_sign, COUNT(runway_sign) as [Anzahl gelandet], 0 as [Anzahl gestartet] FROM tbl_arriving_planes
            GROUP BY runway_sign
    ) as b
    UNION
    SELECT runway_sign as Landebahn, [Anzahl gelandet] ,[Anzahl gestartet]  from
    (
        SELECT runway_sign, 0 as [Anzahl gelandet], COUNT(runway_sign) as [Anzahl gestartet] FROM tbl_leaving_planes
            GROUP BY runway_sign
    ) as a

结果应如下所示:

runway_sign | number of arrived planes | number of leaving planes

2 个答案:

答案 0 :(得分:3)

您可以使用UNION ALL,然后再进行其他聚合:

SELECT runway_sign as Landebahn,
       SUM([Anzahl gelandet]),
       SUM([Anzahl gestartet])
FROM ((SELECT runway_sign, COUNT(runway_sign) as [Anzahl gelandet], 0 as [Anzahl gestartet]
       FROM tbl_arriving_planes
       GROUP BY runway_sign
      ) UNION ALL
      (SELECT runway_sign as Landebahn, 0 as [Anzahl gelandet], COUNT(runway_sign) as [Anzahl gestartet]
       FROM tbl_leaving_planes
       GROUP BY runway_sign
      )
     ) al
GROUP BY runway_sign;

另一种方法使用FULL JOIN而不是UNION ALL

SELECT COALESCE(a.runway_sign, l.runway_sign) as Landebahn,
       a.[Anzahl gelandet],
       l.[Anzahl gestartet]
FROM (SELECT runway_sign, COUNT(runway_sign) as [Anzahl gelandet]
      FROM tbl_arriving_planes
      GROUP BY runway_sign
     ) a FULL JOIN
     (SELECT runway_sign as Landebahn, COUNT(runway_sign) as [Anzahl gestartet]
      FROM tbl_leaving_planes
      GROUP BY runway_sign
     ) l
     ON l.runway_sign = a.runway_sign

答案 1 :(得分:1)

听起来您想对UNION的结果进行分组

SELECT runway_sign as Landebahn, SUM([Anzahl gelandet]) as [Anzahl gelandet], SUM([Anzahl gestartet]) as [Anzahl gestartet]
FROM (
    SELECT runway_sign, 1 as [Anzahl gelandet], 0 as [Anzahl gestartet] FROM tbl_arriving_planes
    UNION
    SELECT runway_sign, 0 as [Anzahl gelandet], 1 as [Anzahl gestartet] FROM tbl_leaving_planes
) as a
GROUP BY runway_sign