我正在尝试从历史航班表中查找以前的航班,我只有1个历史表,其中包括飞机的机尾号和预定的日期出发,我想用该飞机先前的航班信息来创建一个新表,下面是表格示例
原始表:
|flight number|scheduled departure flight|
| A | 1 Jan 2018 10:00 |
| A | 1 Jan 2018 19:00 |
| B | 1 Jan 2018 11:00 |
| B | 1 Jan 2018 19:00 |
| B | 1 Jan 2018 21:00 |
预期结果:
|flight number|scheduled departure flight| previous scheduled departure |
| A | 1 Jan 2018 10:00 | NULL |
| A | 1 Jan 2018 19:00 | 1 Jan 10:00 |
| B | 1 Jan 2018 11:00 | NULL |
| B | 1 Jan 2018 19:00 | 1 Jan 2018 11:00 |
| B | 1 Jan 2018 21:00 | 1 jan 2018 19:00 |
我已经做了一天,感谢您的任何帮助
答案 0 :(得分:0)
您正在寻找LAG
窗口函数,但支持高于8.0的mysql版本
您可以尝试使用子查询来实现lag
窗口功能。
模式(MySQL v5.7)
查询#1
SELECT `flight number`,
`scheduled departure flight`,
(select `scheduled departure flight`
from T tt
where t1.`scheduled departure flight` > tt.`scheduled departure flight`
AND t1.`flight number` = tt.`flight number`
order by tt.`scheduled departure flight` desc
limit 1
) 'previous scheduled departure'
FROM T t1;
| flight number | scheduled departure flight | previous scheduled departure |
| ------------- | -------------------------- | ---------------------------- |
| A | 2018-06-01 10:00:00 | |
| A | 2018-06-01 19:00:00 | 2018-06-01 10:00:00 |
| B | 2018-06-01 11:00:00 | |
| B | 2018-06-01 19:00:00 | 2018-06-01 11:00:00 |
| B | 2018-06-01 21:00:00 | 2018-06-01 19:00:00 |
如果您的mysql版本支持LAG
,则可以尝试此操作。
模式(MySQL v8.0)
CREATE TABLE T(
`flight number` varchar(5),
`scheduled departure flight` datetime
);
INSERT INTO T VALUES ('A','2018-06-01 10:00');
INSERT INTO T VALUES ('A','2018-06-01 19:00');
INSERT INTO T VALUES ('B','2018-06-01 11:00');
INSERT INTO T VALUES ('B','2018-06-01 19:00');
INSERT INTO T VALUES ('B','2018-06-01 21:00');
查询#1
SELECT `flight number`,
`scheduled departure flight`,
LAG(`scheduled departure flight`) OVER(PARTITION BY `flight number` ORDER BY `scheduled departure flight`) 'previous scheduled departure'
FROM T t1;