简体   繁体   中英

How can I merge two tables in a query?

I have two tables in my database, one for leaving planes and one for arriving planes. Each of them includes a column which contains the runway sign. Now I want to make a query where I combine the two tables and count how many planes have arrived at the runway and how many have left.

This is my attempt:

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

Result should look like this:

runway_sign | number of arrived planes | number of leaving planes

You can use UNION ALL followed by another aggregation:

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;

An alternative method uses FULL JOIN rather than 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

It sounds like you want to group on the result of the 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

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