在SQL中合并和计数2个表

时间:2019-12-13 10:29:45

标签: sql

我一直在努力寻找合适的答案,因此,我将非常感谢您的帮助。

我有2个表要合并...

Table1包含机场/车站数据:

id  | name     | country
----+----------+--------
ABC | Paris    | France
DEF | New York | USA
GHI | Madrid   | Spain

Table2包含预订数据:

bid | origin | destination | vehicle
----+--------+-------------+--------
123 | ABC    | XYZ         | plane
456 | XYZ    | GHI         | train
789 | GHI    | XYZ         | bus
999 | DEF    | ABC         | plane

我想要一个完成的表格,该表格显示每辆飞机在每个机场/车站上我们有多少预订,因此看起来像这样:

id  | name     | country | bookings | plane | train | bus
----+----------+---------+----------+-------+-------+----
ABC | Paris    | France  | 2        | 2     | 0     | 0
DEF | New York | USA     | 1        | 1     | 0     | 0        
GHI | Madrid   | Spain   | 2        | 0     | 1     | 1      

有什么办法吗?

到目前为止,我在这里

SELECT a.id, a.name, a.country, vehicle_type, count(bid)
FROM Table2
LEFT JOIN Table1 a ON a.id = origin <> destination
GROUP BY id, name, country, vehicle_type

1 个答案:

答案 0 :(得分:1)

您可以将SUMCASE结合使用以下解决方案来计算不同列中的车辆:

SELECT t1.id, t1.name, t1.country,
  COUNT(bid) AS bookings,
  SUM(CASE WHEN t2.vehicle = 'plane' THEN 1 ELSE 0 END) AS plane,
  SUM(CASE WHEN t2.vehicle = 'train' THEN 1 ELSE 0 END) AS train,
  SUM(CASE WHEN t2.vehicle = 'bus' THEN 1 ELSE 0 END) AS bus
FROM Table1 t1 INNER JOIN Table2 t2 ON t1.id = t2.origin OR t1.id = t2.destination
GROUP BY t1.id, t1.name, t1.country
ORDER BY t1.id ASC

demo on dbfiddle.uk

注意::如果您想查看每个车站/机场(也没有预订),可以使用 LEFT JOIN而不是INNER JOIN