如何按星期几的时间表分组航班?

时间:2014-10-27 18:13:21

标签: mysql sql

那是我的名为“航班”的表格:

| 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那样的一周中的日期。

1 个答案:

答案 0 :(得分: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一起。