分組行我有問題的設備表記錄日期,如:SQL類型和ID
CREATE TABLE myTable
(`device_id` int, `datetime` datetime, `action` varchar(3))
;
INSERT INTO myTable
(`device_id`, `datetime`, `action`)
VALUES
(1, '2015-08-01 11:00', 'out'),
(1, '2015-08-01 11:05', 'out'),
(1, '2015-08-01 11:10', 'out'),
(1, '2015-08-01 11:15', 'out'),
(1, '2015-08-01 11:20', 'out'),
(2, '2015-08-01 11:25', 'out'),
(3, '2015-08-01 11:22', 'out'),
(4, '2015-08-01 11:45', 'out'),
(1, '2015-08-01 12:00', 'in'),
(1, '2015-08-01 12:01', 'in'),
(1, '2015-08-01 12:02', 'in'),
(1, '2015-08-01 12:03', 'in'),
(1, '2015-08-01 12:04', 'in'),
(1, '2015-08-01 12:05', 'in'),
(1, '2015-08-01 12:10', 'out'),
(2, '2015-08-01 12:12', 'in'),
(3, '2015-08-01 12:12', 'in'),
(3, '2015-08-01 12:22', 'out'),
(4, '2015-08-01 12:23', 'in'),
(1, '2015-08-01 08:00', 'in'),
(3, '2015-08-01 09:12', 'in')
;
例如如何分組的「出」和行「在「設備到一排?像:
datetime_out | datetime_in | device_id |
-----------------+------------------+-----------+
2015-08-01 11:00 | 2015-08-01 12:05 | 1 |
2015-08-01 11:25 | 2015-08-01 12:12 | 2 |
2015-08-01 11:22 | 2015-08-01 12:12 | 3 |
2015-08-01 11:45 | 2015-08-01 12:23 | 4 |
2015-08-01 12:10 | 2015-09-03 08:00 | 1 |
2015-08-01 12:22 | 2015-09-03 09:12 | 3 |
UPD:
任何實例,數據庫管理系統並不重要。
如果我有多個「out」或行「中的」與序列相同DEVICE_ID隨後選擇行,最大的日期時間「在」用於和分鐘的日期時間爲「出」,例如:
datetime | device_id | action |
-----------------+-----------+--------+
2015-08-01 11:00 | 1 | out | <- Out 1 device
2015-08-01 11:05 | 1 | out | <- ignore
2015-08-01 11:10 | 1 | out | <- ignore
2015-08-01 11:15 | 1 | out | <- ignore
2015-08-01 11:20 | 1 | out | <- ignore
2015-08-01 11:25 | 2 | out |
2015-08-01 11:22 | 3 | out |
2015-08-01 11:45 | 4 | out |
2015-08-01 12:00 | 1 | in | <- ignore
2015-08-01 12:01 | 1 | in | <- ignore
2015-08-01 12:02 | 1 | in | <- ignore
2015-08-01 12:03 | 1 | in | <- ignore
2015-08-01 12:04 | 1 | in | <- ignore
2015-08-01 12:05 | 1 | in | <- In 1 device
2015-08-01 12:10 | 1 | out | <- Out 1 device
2015-08-01 12:12 | 2 | in |
2015-08-01 12:12 | 3 | in |
2015-08-01 12:22 | 3 | out |
2015-08-01 12:23 | 4 | in |
2015-08-03 08:00 | 1 | in | <- In 1 device
2015-08-03 09:12 | 3 | in |
你怎麼知道行是否匹配?如果在外出前有多個輸入,反之亦然? –
我可以猜測,對於每一個,你都希望按照datetime順序排列下一個,但是你真的應該在你的問題中澄清一下。 – nycdan
你正在使用哪些DBMS? –