0

我想每小时跟踪机器停机时间/生产输出。假设下面是来自 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
4

0 回答 0