MySQL依靠子查询分组

时间:2018-08-29 11:49:28

标签: mysql sql group-by

我正在尝试对某些航班(称为航段)进行SQL查询。目的是要知道有多少航班准时,有5到15分钟之间的延误以及有超过15分钟的延误。

使用子查询,我获得了第一个结果:

SELECT 
    count(*) as 'leg total',
    leg2.l2count as 'less than 15min delay',
    round(leg2.l2count / count(*) * 100, 2) as 'less than 15min delay percentage',
    leg3.l3count as 'more than 15min delay',
    round(leg3.l3count / count(*) * 100, 2) as 'more than 15min delay percentage',
    count(*) - leg2.l2count - leg3.l3count as 'on time',
    round((count(*) - leg2.l2count - leg3.l3count) / count(*) * 100, 2) as 'on time percentage' 
FROM TBL_leg leg -- previsional dates
JOIN TBL_flight_reports fr ON leg.id = fr.leg_ops_id, -- realized dates
(
    SELECT count(l2.id) as l2count
    FROM TBL_leg l2
    JOIN TBL_flight_reports fr2 ON l2.id = fr2.leg_ops_id
    WHERE (
        timediff(fr2.arrival_date_block, l2.to_date_time) > SEC_TO_TIME(5*60) AND
        timediff(fr2.arrival_date_block, l2.to_date_time) < SEC_TO_TIME(15*60)
    )
    OR (
        timediff(fr2.departure_date_block, l2.start_date_time) > SEC_TO_TIME(5*60) AND
        timediff(fr2.departure_date_block, l2.start_date_time) < SEC_TO_TIME(15*60)
    )
) leg2, -- delays between threshold and 15min
(
    SELECT count(l3.id) as l3count
    FROM TBL_leg l3
    JOIN TBL_flight_reports fr3 ON l3.id = fr3.leg_ops_id
    WHERE (
        timediff(fr3.arrival_date_block, l3.to_date_time) > SEC_TO_TIME(15*60)
    )
    OR (
        timediff(fr3.departure_date_block, l3.start_date_time) > SEC_TO_TIME(15*60)
    )
) leg3 -- delays of more than 15min
;

此查询似乎很好。

现在,我正在尝试对结果进行排序:在我的TBL_leg表中,有一个planet_id列,我想按它对结果进行分组。目的是让我的飞机晚点。

问题是让我的子查询分组。我在那里缺少一些逻辑。

此外,如果您对我的主要问题(当前的查询)有更好的解决方案,请放心:)

致谢

1 个答案:

答案 0 :(得分:0)

确保每个子查询均按飞机ID分组,然后将飞机ID添加到子查询的选择项中,然后按飞机ID进行联接。

例如第二回合:

left join (
    SELECT l2.airplane_id, count(l2.id) as l2count
    FROM TBL_leg l2
    JOIN TBL_flight_reports fr2 ON l2.id = fr2.leg_ops_id
    WHERE (
        timediff(fr2.arrival_date_block, l2.to_date_time) > SEC_TO_TIME(5*60) AND
        timediff(fr2.arrival_date_block, l2.to_date_time) < SEC_TO_TIME(15*60)
    )
    OR (
        timediff(fr2.departure_date_block, l2.start_date_time) > SEC_TO_TIME(5*60) AND
        timediff(fr2.departure_date_block, l2.start_date_time) < SEC_TO_TIME(15*60)
    )
    GROUP BY l2.airplane_id
) leg2 ON leg.airplane_id = leg2.airplane_id

也将总查询分组为plane_id。