mysql选择copy column to another,id no successive

时间:2016-10-18 20:08:26

标签: mysql

我希望获得工作场所所有区域中每个事件的时间间隔,所以我得到的这个表显示了事件发生的时间

ID | area |   TIME 1
01 |  A   |  2016-09-20 14:55:54 
02 |  A   |  2016-09-21 18:00:00
04 |  A   |  2016-09-23 20:14:14
06 |  B   |  2016-09-24 13:52:24
10 |  B   |  2016-09-26 13:33:34
13 |  B   |  2016-09-28 18:22:46

我们可以看到,id不是连续的,因为在查询中过滤了另一个数据,我希望输出如下:

area |          TIME 1       |       TIME 2
 A   |  2016-09-20 14:55:54  | 2016-09-21 18:00:00
 A   |  2016-09-21 18:00:00  | 2016-09-23 20:14:14
 B   |  2016-09-24 13:52:24  | 2016-09-26 13:33:34
 B   |  2016-09-26 13:33:34  | 2016-09-28 18:22:46

有没有办法在select?中使用它?我使用内部联接到#34;时间1",但它得到"时间2"每个"时间1"导致区域A:

    area |          TIME 1       |       TIME 2
     A   |  2016-09-20 14:55:54  | 2016-09-20 14:55:54
     A   |  2016-09-20 14:55:54  | 2016-09-21 18:00:00
     A   |  2016-09-20 14:55:54  | 2016-09-23 20:14:14
     A   |  2016-09-21 18:00:00  | 2016-09-20 14:55:54
     A   |  2016-09-21 18:00:00  | 2016-09-21 18:00:00
     A   |  2016-09-21 18:00:00  | 2016-09-23 20:14:14
     A   |  2016-09-23 20:14:14  | 2016-09-20 14:55:54
     A   |  2016-09-23 20:14:14  | 2016-09-21 18:00:00
     A   |  2016-09-23 20:14:14  | 2016-09-23 20:14:14

1 个答案:

答案 0 :(得分:0)

SQL Fiddle Demo

SELECT *
FROM Table1 T1
JOIN Table1 T2
  ON T1.area = T2.area 
 AND T2.ID = (SELECT MIN(T3.ID) 
              FROM Table1 T3
              WHERE T3.ID > T1.ID
                AND T3.area = T1.area)

<强>输出

enter image description here

编辑:我假设ID_1 < ID_2然后Time_1 < Time_2