2014-10-27 21 views
1

這是我的表名爲「航班」:如何按時間表將航班分組?

| ORIGIN | DESTINATION | DAY_OF_WEEK | DEPARTURE_HOUR | FLIGHT_NUMBER | AIRLINE  | 
------------------------------------------------------------------------------------- 
| FRA | MAD  |  1  |    |    | Lufthansa | 
| FRA | MAD  |  3  |    |    | Lufthansa | 
| FRA | MAD  |  6  |    |    | Lufthansa | 
| LHR | MUC  |  1  |    |    | Lufthansa | 
| LHR | MUC  |  2  |    |    | Alitalia | 
| JFK | EWR  |  5  |    |    | Delta  | 
| BCN | MAD  |  7  |    |    | Ryanair  | 
| FRA | MAD  |  7  |    |    | Lufthansa | 
| FRA | MAD  |  1  |    |    | Iberia  | 

的問題是,如何讓時間表由始發地,目的地,航空公司和星期分組,像這樣:

FRA -> MAD 1*3**6*7 Lufthansa 
FRA -> MAD 1******* Iberia 
LHR -> MUC 12****** Alitalia 
JFK -> EWR ****5*** Delta 
BCN -> MAD *******7 Ryanair 

我當前的查詢是:SELECT origin, destination, airline FROM flights GROUP BY origin, destination, airline ORDER BY origin;但正如您所看到的,它不會像1*3*567那樣返回格式化的星期幾。

回答

3

這聽起來像你正試圖pivot你的結果。你可以用MAXCASE做到這一點:

select origin, destination, airline, 
    max(case when day_of_week = 1 then '1' else '*' end) as `1`, 
    max(case when day_of_week = 2 then '2' else '*' end) as `2`, 
    max(case when day_of_week = 3 then '3' else '*' end) as `3`, 
    max(case when day_of_week = 4 then '4' else '*' end) as `4`, 
    max(case when day_of_week = 5 then '5' else '*' end) as `5`, 
    max(case when day_of_week = 6 then '6' else '*' end) as `6`, 
    max(case when day_of_week = 7 then '7' else '*' end) as `7` 
from flights 
group by origin, destination, airline 
order by origin; 

目前尚不清楚,如果這些應該是一列或不 - 我把它們分開,但足以輕鬆concat在一起。

+0

太棒了!謝謝。 – 2014-10-27 19:56:21