【问题标题】:MySQL query for timestamp of change in column valueMySQL查询列值更改的时间戳
【发布时间】:2021-01-06 22:39:00
【问题描述】:

如何查询给定 id 的特定列值更改的日期?下表显示了运行作业以确定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 |                |
 

【问题讨论】:

  • 您使用的是哪个版本的 MySQL?

标签: mysql sql min


【解决方案1】:

你可以使用窗口函数:

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() 用于获取下一个日期。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-21
    • 2014-01-28
    相关资源
    最近更新 更多