python - 选择列与上一行不同的行
问题描述
我正在尝试编写一个查询来跟踪表中布尔列的更改。桌子看起来像这样
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。但这并没有按计划进行。我希望当我触发活动/非活动时,它应该在此查询中交替出现,但事实并非如此。有人有任何提示吗?
解决方案
使用窗口函数!
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;
推荐阅读
- xamarin - ListView 项目在 Xamarin 表单中不展开折叠高度
- jquery - 我可以使用按钮禁用/启用 Google 图表中的滚动吗?
- sed - sed、xargs 和 stdbuf - 如何从文件中仅获取模式的前 n 个匹配项
- r - Spotfire TERR 数据函数中的动态聚合列输入引用
- r - 在 R 中按组计算差异 b/w 日期 - 未解决
- json - 不允许使用“$__”
- c++ - libcurl 在 Windows 服务中崩溃
- java - Java Android - 如何调用 onSuccess 方法
- r - 因子水平重复时锁定因子水平顺序
- ignite - Apache 点燃为什么 odbc/jdbc 驱动被初始化