按设备查找总工时

时间:2016-01-28 09:01:01

标签: sql sqlite

我有一个日志表:processlogmodel

id      log_time               log_type device_id
1061    1/1/2016 9:08:45    PM  False   2
1062    1/1/2016 11:19:45   PM  False   2
1063    1/2/2016 8:44:46    AM  False   2
1064    1/2/2016 3:56:46    AM  True    3
1065    1/2/2016 12:51:46   AM  True    2
1066    1/1/2016 6:33:46    PM  False   2
1067    1/2/2016 8:20:46    AM  False   3
1068    1/2/2016 7:57:46    AM  True    1
1069    1/1/2016 6:21:46    PM  False   1
1070    1/2/2016 8:34:47    AM  False   2
1071    1/2/2016 12:18:47   AM  True    1
1072    1/1/2016 6:14:47    PM  True    3
1073    1/2/2016 8:21:47    AM  True    2
1074    1/2/2016 12:39:47   AM  False   3
1075    1/1/2016 11:23:47   PM  False   1
1076    1/1/2016 8:02:11    PM  True    1
1078    1/2/2016 4:02:12    AM  False   1
1079    1/1/2016 8:02:11    PM  True    2
1080    1/1/2016 10:02:11   PM  True    2
1081    1/1/2016 4:54:11    AM  False   2
1083    1/1/2016 5:47:11    AM  True    2
1084    1/2/2016 4:47:12    AM  False   2
1085    1/2/2016 8:39:12    AM  True    2

如何查找每台设备的总工作时间?

0 表示 on 1 表示 off ,我使用的是sqlite3和Python。

它只是一个日志模型,我添加记录,log_type = 0表示开始工作,log_type = 1表示设备的最终工作时间。 我想要 : 1.通过设备查找连续记录以计算工作持续时间 2.按设备查找总工时。

1 个答案:

答案 0 :(得分:-2)

this is my solution:

SELECT device_id, sum(sub) as total 
FROM (
    SELECT t1.device_id, strftime('%s', t2.log_time)-strftime('%s', t1.log_time) as sub 
    FROM app_processlogmodel AS t1 INNER JOIN app_processlogmodel AS t2
    WHERE t1.device_id = t2.device_id AND
    t1.log_type = 0 AND
    t2.log_type = 1 AND
    t2.log_time > t1.log_time
    GROUP BY t1.id HAVING min(strftime('%s', t2.log_time) - strftime('%s', t1.log_time))
    ORDER BY t1.device_id, t1.log_time
)
GROUP BY device_id

and it works :)