0

我有一张这样的桌子:

CREATE TABLE `hoststatus` (
  `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `host` varchar(100) NOT NULL,
  `result` tinyint(1) NOT NULL,
  PRIMARY KEY (`timestamp`,`host`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

INSERT INTO `hoststatus` (`timestamp`, `host`, `result`) VALUES
('2012-06-08 14:18:01', 'host1', 0),
('2012-06-08 14:19:01', 'host1', 0),
('2012-06-08 14:20:01', 'host1', 1),
('2012-06-08 14:21:01', 'host1', 1),
('2012-06-08 14:22:01', 'host1', 1),
('2012-06-08 14:23:01', 'host1', 1),
('2012-06-08 14:24:01', 'host1', 0),
('2012-06-08 14:25:01', 'host1', 0),
('2012-06-08 14:26:01', 'host1', 0),
('2012-06-08 14:27:01', 'host1', 0),
('2012-06-08 14:28:01', 'host1', 1),
('2012-06-08 14:29:01', 'host1', 1),
('2012-06-08 14:29:04', 'host2', 0),
('2012-06-08 14:30:01', 'host1', 0),
('2012-06-08 14:30:03', 'host2', 0),
('2012-06-08 14:31:01', 'host1', 0),
('2012-06-08 14:32:01', 'host1', 0),
('2012-06-08 14:32:02', 'host2', 1),
('2012-06-08 14:33:01', 'host1', 0);

这包含一些主机的连接状态:1 表示“离线”,0 表示“在线”。我想使用选择请求推断的是每个主机的每个“离线”状态的开始和结束时间戳。在上面的示例中,请求应返回如下内容:

begin                  end                     host
'2012-06-08 14:20:01'  '2012-06-08 14:23:01'   'host1'
'2012-06-08 14:28:01'  '2012-06-08 14:29:01'   'host1'
'2012-06-08 14:32:02'  '2012-06-08 14:32:02'   'host2'

有人可以给我解决这个问题的方法吗?谢谢你。

4

1 回答 1

2

您实际上是在尝试在数据中找到“运行”或“条纹”。这个答案可能会为您提供一些关于如何完成任务的指导。

编辑:针对您的具体问题,链接的答案可以翻译为以下内容:

SELECT
    host,
    MIN(ts) as StartDate, 
    MAX(ts) as EndDate
FROM (
    SELECT
        ts,
        host,
        result,
        (   SELECT
                COUNT(*) 
            FROM
                hoststatus h2 
            WHERE
                h1.host = h2.host
                and h1.result <> h2.result
                and h2.ts >= h1.ts) as rungroup
    FROM
        hoststatus h1) A
WHERE result = 1
GROUP BY host, rungroup
ORDER BY rungroup desc;
于 2012-06-08T19:18:10.927 回答