首页 > 解决方案 > 选择列与上一行不同的行

问题描述

我正在尝试编写一个查询来跟踪表中布尔列的更改。桌子看起来像这样

ClientHistory
-------------------------------------------------------------
| id | client_id | client_name | is_active    |   Timestamp |
-------------------------------------------------------------
| 1 |    1       |Example Client|    True     |   06/15/2020|
-------------------------------------------------------------
| 2 |    1       |Client Change |     True    |   06/16/2020|
-------------------------------------------------------------
| 3 |    1       |Client Change |   False     |  06/17/2020 |

所以我想要的是第 3 行,其中 is_active 更改为 false。然后在那之后我想要下一行它再次变为true。

这是我尝试过的:

        SELECT a.*
        FROM client_history AS a
        WHERE a.is_active <>
            ( SELECT b.is_active
                FROM client_history AS b
                WHERE a.client_id = b.client_id
                AND a.timestamp > b.timestamp
                ORDER BY b.timestamp DESC
                LIMIT 1
            ) 

所以子查询试图通过获取它之前的最新时间戳来获取相同 client_id 的前一行。然后在查询中检查 is_active 是否不等于前一行的 is_active。但这并没有按计划进行。我希望当我触发活动/非活动时,它应该在此查询中交替出现,但事实并非如此。有人有任何提示吗?

标签: pythonmysqlsqlflasksqlalchemy

解决方案


使用窗口函数!

select ch.*
from (select ch.*,
             lag(is_active) over (partition by client_id order by timestamp) as prev_is_active
      from client_history ch
     ) ch
where is_active <> prev_is_active;

推荐阅读