计算两个表的总和

时间:2013-03-18 21:36:15

标签: 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                  2          1
 4         1                2                  1          5
 5         1                3                  1          3

bustypes:

bus_type_id | pollution_output
 1             3
 2             7

例如,城市2每天四次暴露于bus_type 1(route_id 1),bus_type 1每天五次暴露(route_id 4),每天污染产量为27。但我基本上需要为所有城市计算这个并返回污染最严重的城市,我该怎么做?

1 个答案:

答案 0 :(得分:1)

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