数据库
首页 > 数据库> > PHP Mysql从一天中的两个日期时间计算每天的总飞行小时数

PHP Mysql从一天中的两个日期时间计算每天的总飞行小时数

作者:互联网

Row_id Sensor_ID  datetime_takeoff       datetime_landing
1      SFO        2013-09-18 04:34:22    2013-09-19 08:34:22
2      BWI        2013-09-18 04:34:22    2013-09-18 16:55:23 
3      BWI        2013-09-18 20:34:22    2013-09-19 10:34:22   
4      SFO        2013-09-19 15:21:22    2013-09-19 20:34:22   
5      BWI        2013-09-19 20:34:22    2013-09-20 06:15:16   
6      SFO        2013-09-19 23:47:22    2013-09-20 07:59:59   
7      BWI        2013-09-20 11:34:05    2013-09-21 02:05:21   
8      SFO        2013-09-20 10:28:56    NULL   
9      BWI        2013-09-21 04:09:57    NULL         

这是针对PHP和Mysql这些飞机起飞和降落日期时间为两架飞机SFO和BWI.我正在计算每架飞机每天有多少小时.飞行时间很容易,只有DATETIMEDIFF,但空中每天的时间很难证明.

我想我可以分解为两步:
1.对于同一天的任何起飞和降落对,只需获取datetimediff,如果datetime_takeoff和datetime_landing不在同一天,则插入整夜的总小时数.我可以在它发生时运行它.

2.每天午夜运行检查并检查datetime_landing是否为NULL,如果datetime_takeoff是TODAY,那么计算午夜的小时数.如果datetime_takeoff不是今天,则插入24小时的值.我想这将涵盖不在同一天/ NULL的timedate_landings

在处理所有数据的情况下,这种逻辑是否有意义?

解决方法:

也许是这样的?

select
    sensor_ID,
    day,
    sum(flighttime) as sumflighttime
from
(
    (select
        sensor_ID,
        date_format(datetime_takeoff, '%Y-%m-%d') as day,
        case
            when date_format(datetime_takeoff, '%d') = date_format(datetime_landing, '%d')
                then subtime(datetime_landing, datetime_takeoff)
            else subtime(date_format(datetime_landing, '%Y-%m-%d'), datetime_takeoff)
        end flighttime
    from
        datatable
    ) b
    union all
    (select
        sensor_ID,
        date_format(datetime_landing, '%Y %m %d') as day,
        subtime(datetime_landing, date_format(datetime_landing, '%Y-%m-%d')) flighttime
    from
        datatable
    where
        date_format(datetime_takeoff, '%d') != date_format(datetime_landing, '%d')
    ) b
) t
group by
    sensor_ID,
    day

标签:php,mysql,sql,dateinterval
来源: https://codeday.me/bug/20190708/1407585.html