2012-06-08 182 views
0

我有這樣的一個表:MYSQL:選擇時間範圍使用時間戳列和分組

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是「在線」。我想要使​​用select請求推斷的是每個主機的每個「脫機」狀態的開始和結束時間戳。在上面的例子中,請求應該返回是這樣的:

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' 

能有人給我的方式來解決這個問題嗎?謝謝。

回答

2

你基本上試圖在你的數據中找到「運行」或「條紋」。 This answer可能會爲您提供一些關於如何完成任務的指導。

編輯:鏈接的答案可以被翻譯爲您的具體問題如下:

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; 
+0

非常感謝你,這是完美的。 –