Sql 从两个表中计算聚合和

Sql 从两个表中计算聚合和,sql,postgresql,aggregate-functions,Sql,Postgresql,Aggregate Functions,从下表中,我需要确定哪个城市的公交车污染最严重 路线: route_id | departure_city | destination_city | bus_type | times_per_day 1 2 1 1 4 2 1 3 2 2 3 3 1

从下表中,我需要确定哪个城市的公交车污染最严重

路线:

route_id | departure_city | destination_city | bus_type | times_per_day
 1         2                1                  1          4
 2         1                3                  2          2
 3         3                1                  2          1
 4         1                2                  1          5
 5         1                3                  1          3
胸围:

bus_type_id | pollution_output
 1             3
 2             7

例如,城市2每天接触1型公共汽车4次(路线1号)和1型公共汽车5次(路线4号),每天产生27次污染输出。但我基本上需要为所有的城市计算并返回最大污染的城市,我该怎么做?< / P>如果你解决了这个问题,考虑一下。
SELECT city, sum(pollution) AS total_pollution
FROM (
   SELECT r.depature_city AS city
         ,b.pollution_output * r.times_per_day AS pollution
   FROM   routes   r
   JOIN   bustypes b ON b.bus_type_id = r.bus_type

   UNION ALL
   SELECT r.destination_city
         ,b.pollution_output * r.times_per_day
   FROM   routes   r
   JOIN   bustypes b ON b.bus_type_id = r.bus_type
   ) AS sub
GROUP  BY city