2014-09-24 105 views
0

我有預定時間的表的事件和實際時間事件發生第二之間,例如:計算「按時履約」計劃時間和實際時間

Table A 
ID Date   Scheduled 
1  2014-09-01 07:05:00 
2  2014-09-02 07:05:00 
3  2014-09-03 08:05:00 
4  2014-09-04 07:10:00 

Table B 
ID Date   Actual 
1  2014-09-01 07:10:00 
2  2014-09-02 07:16:00 
3  2014-09-03 08:00:00 
4  2014-09-04 14:15:00 

如果我們假設中的任何10分鐘的時間表被認爲是「準時」,是否有辦法使用MySQL返回「準時性能」?在上面的數據集中,按時間表現將是50%,因爲兩個事件在時間表的10分鐘內發生。

補充編輯:如果一個事件是早期,這也將在當時被認爲是

回答

1

是。但是,我不明白爲什麼日期和時間在不同的列中。你只需要兩個表連接在一起,做一些有條件的邏輯:

select avg(case when a.date = b.date and a.actual <= a.scheduled + interval 10 minute then 1 
       when b.date < a.date then 1 
       else 0 
      end) as OnTimePerformance 
from tablea a join 
    tableb b 
    on a.id = b.id; 

這不處理其中,事件被安排在第一天的情況下(比如下午11時55分)和實際時間是第二天(上午12:01)。你的數據表明這不會發生。如果日期和時間在單個列中,這種情況會更容易。

1

這裏是做

select 
round((on_time/tot)*100) as performance 
from 
(
select 
count(*) as tot, 
sum(
    case when 
    timestampdiff(minute,concat(t1.Date,' ',t1.Scheduled),concat(t2.Date,' ',t2.Actual)) < 10 
    then 1 
    end 
) as on_time 
from tableA t1 
join tableB t2 on t1.id = t2.id 
)p; 

DEMO

的另一種方式