在一個表中,我有如下所示的時間序列資料:
| t_stamp | status_val |
|---|---|
| 2022-04-21 上午 8:00 | 0 |
| 2022-04-21 上午 8:01 | 0 |
| 2022-04-21 8:02 AM | 3 |
| 2022-04-21 8:03 AM | 1 |
| 2022-04-21 8:04 AM | 1 |
| 2022-04-21 上午 8:05 | 0 |
上面的例子非常簡化。實際上,時間戳是每秒,status_val 可能對于 100 行相同,然后才看到不同的值。
嘗試撰寫一個選擇第一行和 status_val 的查詢,然后下一行是 status_val 實際更改的時間。所以輸出應該是這樣的:
| t_stamp | status_val |
|---|---|
| 2022-04-21 上午 8:00 | 0 |
| 2022-04-21 8:02 AM | 3 |
| 2022-04-21 8:03 AM | 1 |
| 2022-04-21 上午 8:05 | 0 |
幾乎就像LEAD(status_val,1) <> status_val在 WHERE 子句中使用 a 一樣……但這顯然不適用于 WHERE 子句。
我嘗試過使用 group by 和 distinct,但結果不是預期的輸出。不是postgres的專家,所以請溫柔:)
uj5u.com熱心網友回復:
用于LAG()確定在 CTE 中保留哪些行:
with mark_repeats as (
select t_stamp, status_val,
coalesce(
status_val = lag(status_val) over (order by t_stamp),
false
) as is_repeat
from your_table
)
select t_stamp, status_val
from mark_repeats
where not is_repeat;
作業示例
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/467664.html
標籤:PostgreSQL
上一篇:OperationalError:(psycopg2.OperationalError)無法將主機名“143@postgres”轉換為地址:未知服務器錯誤
