2013-03-18 72 views
0

從下面的表格中我需要確定哪個城市巴士受污染最嚴重。從兩個表中計算總計總和

路線:

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 5次,每天(ROUTE_ID 4)每天的污染量爲27。但我基本上需要爲所有城市計算這個數據,並返回污染最嚴重的那個,我該怎麼做?

+0

如果解決了您的問題,請考慮[接受答案](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) – 2013-03-19 16:19:43

回答

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