這是基本思想......它將結果選擇爲單row and
列, which you can then fetch with
PHP` ...
此解決方案假定停止&開始成對出現的,即:一開始的ID將是+1
是停止的。否則,你應該SELECT/JOIN
的ID是>
那個停止的,並且LIMIT
它到1
。
自加入可能不會產生最佳的性能,所以要小心並測量一些數據的執行時間以確保安全。
http://sqlfiddle.com/#!9/de72bf/1
CREATE TABLE fillercdown (
`fillercdown_ndx` int(11) NOT NULL AUTO_INCREMENT,
`time` datetime DEFAULT NULL,
`B3_4_5` int(11) DEFAULT NULL,
PRIMARY KEY (`fillercdown_ndx`),
KEY `fillercdowntimendx` (`time`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=latin1;
INSERT INTO fillercdown
(`time`, `B3_4_5`)
VALUES
('2016-06-16 14:00:45', 0),
('2016-06-16 14:01:00', 1),
('2016-06-16 16:00:00', 0),
('2016-06-16 16:01:00', 1)
;
SELECT SUM(TIMEDIFF(g.`time`, f.`time`))
FROM fillercdown f
INNER JOIN fillercdown g
ON g.`fillercdown_ndx` = (f.`fillercdown_ndx` + 1)
AND g.`B3_4_5` = 1
AND TIME(g.`time`) BETWEEN '08:00:00' AND '17:00:00'
WHERE f.`B3_4_5` = 0
AND TIME(f.`time`) BETWEEN '08:00:00' AND '17:00:00'
如果你想包括倍所在的機器停止,但尚未重新啓動,你可以做這樣的事情:
http://sqlfiddle.com/#!9/d113b9/9
INSERT INTO fillercdown
(`time`, `B3_4_5`)
VALUES
('2016-06-16 14:00:45', 0),
('2016-06-16 14:01:00', 1),
('2016-06-16 16:00:00', 0),
('2016-06-16 16:01:00', 1),
('2016-06-16 16:02:00', 0)
;
SELECT SUM(TIMEDIFF(COALESCE(g.`time`, '2016-06-16 16:02:01'), f.`time`))
FROM fillercdown f
LEFT JOIN fillercdown g
ON g.`fillercdown_ndx` = (f.`fillercdown_ndx` + 1)
AND g.`B3_4_5` = 1
AND TIME(g.`time`) BETWEEN '08:00:00' AND '17:00:00'
WHERE TIME(f.`time`) BETWEEN '08:00:00' AND '17:00:00' AND f.`B3_4_5` = 0
你可以取代2016-06-16 16:02:01
與NOW()
或基於f.time
的東西,它取決於當然你的應用需求。
如果您從不想獲得NULL
,而是0
,如果沒有匹配的行,請執行如下操作:COALESCE(SUM(...), 0)
。
如果你喜歡一個腳本型解決方案,你總是可以做這樣的事情:
SELECT f.`time`, f.`B3_4_5`
FROM fillercdown f
WHERE TIME(f.`time`) BETWEEN '08:00:00' AND '17:00:00'
,然後計算總和,像這樣(僞代碼):
stopped = null;
pairs = []
for (row in rows)
if (row.isStopped) stopped = row
else
pairs += [stopped, row]
stopped = null
sum = 0
for (pair in pairs)
sum += duration(pair[0], pair[1])
我假設'fillercdown_ndx'是主鍵......你能不能添加'CREATE TABLE'這個表你的問題?另外:你是否想知道從特定的'0'到下一個出現'1'的持續時間,即:你知道'fillercdown_ndx'嗎? b)來自所有? c)平均? – Centril
更新我希望這解釋更多。對不起,我真的還在學習,但盡我所能。這就讓我卡住了 –
所以如果我正確地理解了這個問題,你想在小時X和Y內選擇所有(0,1)對,然後計算這些間隔的總和? – Centril