56,677
社区成员
发帖
与我相关
我的任务
分享
CREATE TABLE `hp_report` (
`id` int(10) unsigned NOT NULL auto_increment,
`code` varchar(255) NOT NULL,
`content` mediumtext NOT NULL,
`ctime` datetime NOT NULL,
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=662555 ;
INSERT INTO `hp_report` VALUES (2, 'a', 'on', '2014-07-04 21:17:53');
INSERT INTO `hp_report` VALUES (3, 'a', 'abc', '2014-07-04 21:18:53');
INSERT INTO `hp_report` VALUES (4, 'a', 'off', '2014-07-04 21:19:53');
INSERT INTO `hp_report` VALUES (5, 'b', 'on', '2014-07-04 21:20:53');
INSERT INTO `hp_report` VALUES (6, 'b', 'abc', '2014-07-04 21:22:53');
INSERT INTO `hp_report` VALUES (7, 'b', 'off', '2014-07-04 21:29:53');
INSERT INTO `hp_report` VALUES (8, 'a', 'on', '2014-07-04 21:34:53');
INSERT INTO `hp_report` VALUES (9, 'a', 'abc', '2014-07-04 21:36:53');
INSERT INTO `hp_report` VALUES (10, 'a', 'off', '2014-07-04 21:45:53');
INSERT INTO `hp_report` VALUES (11, 'b', 'on', '2014-07-04 22:12:53');
INSERT INTO `hp_report` VALUES (13, 'b', 'abc', '2014-07-04 22:18:53');
INSERT INTO `hp_report` VALUES (14, 'b', 'off', '2014-07-04 22:19:53');
INSERT INTO `hp_report` VALUES (4, 'a', 'off', '2014-07-04 21:19:53');
和
INSERT INTO `hp_report` VALUES (2, 'a', 'on', '2014-07-04 21:17:53');
之间ctime的差值(2分钟)
INSERT INTO `hp_report` VALUES (8, 'a', 'on', '2014-07-04 21:34:53');
INSERT INTO `hp_report` VALUES (10, 'a', 'off', '2014-07-04 21:45:53');
这个是11分钟。
并把a只有所有的差值加起来。
我要的结果是
a 13
b 16
//只适合每条on的数据都有对应的off情况使用
set @on := 0,@off := 0;
select m.`code`,sum(m.mtime)mtime from
(
select a.`code`,((UNIX_TIMESTAMP(b.ctime) - UNIX_TIMESTAMP(a.ctime)) / 60)as mtime from
(
select (@on := @on + 1)as `on`,id,`code`,ctime from hp_report where content = 'on' order by ctime
)a
left join
(
select (@off := @off + 1)as `off`,id,`code`,ctime from hp_report where content = 'off' order by ctime
)b
on a.code = b.code and a.`on` = b.`off`
)m
group by m.`code`;
mysql> select * from hp_report;
+----+------+---------+---------------------+
| id | code | content | ctime |
+----+------+---------+---------------------+
| 2 | a | on | 2014-07-04 21:17:53 |
| 3 | a | abc | 2014-07-04 21:18:53 |
| 4 | a | off | 2014-07-04 21:19:53 |
| 5 | b | on | 2014-07-04 21:20:53 |
| 6 | b | abc | 2014-07-04 21:22:53 |
| 7 | b | off | 2014-07-04 21:29:53 |
| 8 | a | on | 2014-07-04 21:34:53 |
| 9 | a | abc | 2014-07-04 21:36:53 |
| 10 | a | off | 2014-07-04 21:45:53 |
| 11 | b | on | 2014-07-04 22:12:53 |
| 13 | b | abc | 2014-07-04 22:18:53 |
| 14 | b | off | 2014-07-04 22:19:53 |
+----+------+---------+---------------------+
12 rows in set (0.00 sec)
mysql> select `code`,sum(k) from (
-> select `code`,
-> TIMESTAMPDIFF(MINUTE,(select max(ctime) from hp_report where `code`=a.code and ctime<a.ctime),ctime) as k
-> from hp_report a
-> where content='off'
-> ) t
-> group by `code`;
+------+--------+
| code | sum(k) |
+------+--------+
| a | 10 |
| b | 8 |
+------+--------+
2 rows in set (0.00 sec)
mysql>