mysql按子查询分组计数

dm7nw8vv  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(304)

我正在尝试对一些航班(称为legs)进行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\u leg表中,有一个airplane\u id列,我想按它对结果进行分组。目的是让我在飞机上耽搁。
问题是如何在子查询中获取分组。我不太懂逻辑。
另外,如果您对我的主要问题(我当前的查询)有更好的解决方案,请随意:)
当做

brccelvz

brccelvz1#

确保每个子查询按飞机id分组,并将飞机id添加到子查询的select中,然后按飞机id联接。
e、 g.第二段:

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

也将总查询分组到您的id上。

相关问题