1

我有一张这样的桌子

Id    Status        TimeStamp
1        1     2012-02-03 00:00:05
2        1     2012-02-03 00:00:10
3        0     2012-02-03 00:00:15
4        0     2012-02-03 00:00:20
5        0     2012-02-03 00:00:25
6        1     2012-02-03 00:00:30
7        1     2012-02-03 00:00:35
8        1     2012-02-03 00:00:40
9        0     2012-02-03 00:00:45
10       1     2012-02-03 00:00:50

我正在使用 MySQL。我需要的是一个 sql 查询或存储过程,它只选择具有 ID 的行(1、2、3、5、6、8、9、10)。即,在按时间戳排序后,我需要一系列相同“状态”记录中的第一条和最后一条记录。这实际上可行吗?帮助!!!

4

1 回答 1

1
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table 
(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,status        TINYINT NOT NULL
,TimeStamp TIMESTAMP NOT NULL
);

INSERT INTO my_table VALUES
(1        ,1     ,'2012-02-03 00:00:05'),
(2        ,1     ,'2012-02-03 00:00:10'),
(3        ,0     ,'2012-02-03 00:00:15'),
(4        ,0     ,'2012-02-03 00:00:20'),
(5        ,0     ,'2012-02-03 00:00:25'),
(6        ,1     ,'2012-02-03 00:00:30'),
(7        ,1     ,'2012-02-03 00:00:35'),
(8        ,1     ,'2012-02-03 00:00:40'),
(9        ,0     ,'2012-02-03 00:00:45'),
(10       ,1     ,'2012-02-03 00:00:50');

SELECT a.id start
     , MIN(c.id) End 
  FROM my_table a
  LEFT 
  JOIN my_table b 
    ON b.status = a.status
   AND b.id = a.id - 1
  LEFT 
  JOIN my_table c 
    ON c.status = a.status
   AND c.id >= a.id  
  LEFT 
  JOIN my_table d 
    ON d.status = a.status
   AND d.id = c.id + 1
 WHERE b.id IS NULL 
   AND c.id IS NOT NULL
   AND d.id IS NULL
 GROUP 
    BY a.id; 

+-------+------+
| start | End  |
+-------+------+
|     1 |    2 |
|     3 |    5 |
|     6 |    8 |
|     9 |    9 |
|    10 |   10 |
+-------+------+

这是一个相同的小提琴

于 2013-05-14T10:45:09.770 回答