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小时的值。我想这将涵盖不在同一天的timedate_landings / NULL
在处理所有数据的情况下,这种逻辑是否有意义?
答案 0 :(得分:1)
也许是这样的?
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