mysql:每小时/每日从日期范围开始的停机时间

时间:2016-01-24 14:19:25

标签: php mysql downtime

我想按小时跟踪机器停机时间/产量。假设以下是来自2个表的数据。我使用的是unix时间戳,但是对于这个例子,我使用了日期/时间来轻松引用

Table 1 - Output
mc    date/time         output       
1    2015-01-24 00:00   10
1    2015-01-24 01:30   5
1    2015-01-24 04:00   5
1    2015-01-24 04:30   10

Table 2 - Downtime        
mc   machine stop        machine start
1    2015-01-24 02:15    2015-01-24 03:55




Output I need

mc   date     hr      output         downtime
1    24 Jan   0       10             0
1    24 Jan   1       5              0
1    24 Jan   2       0              45min ( since machine stopped at 02:25 )
1    24 Jan   3       0              55min ( since machine up at 03:55 )

....等等

编辑: 这将是一个24小时滚动报告,因此小时和日期将是动态的

感谢您对此的帮助,我希望该解决方案也适用于每月查询

添加--- 这是我到目前为止最好的,sqlfiddle在

之下
SELECT lt.date, lt.mc, lt.output, rt.dt FROM 
     (SELECT mc, DATE_FORMAT(FROM_UNIXTIME(timestamp),'%Y%m%d %H:00') as date, 
       sum(output) as output   
       FROM production 
       GROUP BY 
      DATE_FORMAT(FROM_UNIXTIME(timestamp),'%Y%m%d %H:00')
     ) lt
LEFT JOIN (
      SELECT DATE_FORMAT(FROM_UNIXTIME(machine_stop),'%Y%m%d %H:00') as date,
             machine_stop,
             sum(machine_start-machine_stop) as dt, mc  
      FROM downtime 
      GROUP BY 
           DATE_FORMAT(FROM_UNIXTIME(machine_stop),'%Y%m%d %H:00') 
       ) AS rt   
ON   lt.date= rt.date  
UNION 
SELECT rt.date, rt.mc, lt.output, rt.dt FROM 
     (SELECT mc, DATE_FORMAT(FROM_UNIXTIME(timestamp),'%Y%m%d %H:00') as date, 
       sum(output) as output   
       FROM production 
       GROUP BY 
      DATE_FORMAT(FROM_UNIXTIME(timestamp),'%Y%m%d %H:00')
     ) lt
RIGHT JOIN (
      SELECT DATE_FORMAT(FROM_UNIXTIME(machine_stop),'%Y%m%d %H:00') as date,
             machine_stop,
             sum(machine_start-machine_stop) as dt, mc  
      FROM downtime 
      GROUP BY 
           DATE_FORMAT(FROM_UNIXTIME(machine_stop),'%Y%m%d %H:00') 
       ) AS rt   
ON   lt.date= rt.date 
ORDER BY date asc

0 个答案:

没有答案