MySQL 查询列值变化的时间戳

MySQL query for timestamp of change in column value

如何查询给定 ID 的特定列值更改的日期?下面的 table 显示工作 运行 的日期,确定 oppid 的状态。我想跟踪 oppid 何时具有 status = status_1 以显示设置状态的最早日期和状态为 <> status_1 的日期。

| oppid  |    date   |  status   |
+--------+  ---------+-----------+
| 1000   | 2020-07-01|  status_1 |
| 1000   | 2020-07-02|  status_1 |
| 1000   | 2020-07-03|  status_1 |
| 1000   | 2020-07-04|  status_2 |
| 1000   | 2020-07-07|  status_2 |
| 1000   | 2020-07-15|  status_1 |
| 1000   | 2020-07-16|  status_1 |
| 1001   | 2020-07-10|  status_1 |
| 1001   | 2020-07-11|  status_1 |
| 1000   | 2020-08-01|  status_2 |

期望的结果如下所示:

| oppid  |   status  |  status_set | status_changed |
+--------+  ---------+-------------+----------------+
| 1000   | status_1  |  2020-07-01 |   2020-07-04   |
| 1000   | status_1  |  2020-07-15 |   2020-08-01   |
| 1001   | status_1  |  2020-07-10 |                |
 

您可以使用 window 函数:

select oppid, status, date as status_set, status_changed
from (select t.*,
             lag(status) over (partition by oppid order by date) as prev_status,
             min(case when status <> 'status_1' then date end) over (partition by oppid order by date desc) as status_changed
      from t
     ) t
where (prev_status is null or prev_status <> status) and
      status = 'status_1';

每次状态变为'status_1'时,使用之前的状态进行过滤查找。当状态不是 'status_1'.

时,min() 用于获取下一个日期