python—选择列与前一行不同的行

iyfamqjs  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(203)

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

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\u active变为false。然后在那之后,我希望下一行它再次变为真。
这就是我所尝试的:

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
            )

因此,子查询试图通过获取前一行的最新时间戳来获取同一客户机id的前一行。然后在查询中检查is\u active是否等于前一行的is\u active。但这并没有按计划进行。我希望当我触发ACTIVE/inactive时,它应该在这个查询中交替出现,但事实并非如此。有人有小费吗?

ldfqzlk8

ldfqzlk81#

使用窗口功能!

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;

相关问题