所以我有一張vehicle_states這樣的表:
vehicle_id | state | updated_at
------------ ---------------- -------------------------------
ACX-685 | idle | 2021-12-24 15:13:09.071822 00
ACX-685 | active | 2021-12-24 16:03:41 00
ACX-685 | out-of-service | 2021-12-24 16:15:34.822808 00
ACX-685 | idle | 2021-12-24 16:15:35.822808 00
ACX-685 | active | 2021-12-24 16:40:23 00
ACX-685 | idle | 2021-12-24 16:40:37.436949 00
ACX-685 | active | 2021-12-24 16:40:38 00
對于每輛車和停止服務狀態,我想找出從這種狀態轉換出來所需的時間。車輛停止使用的時間。
我想得到一個表,其中包含車輛 ID、車輛停止服務時的時間戳以及指定車輛停止服務的時間間隔的第三列,如下所示:
vehicle_id | out_of_service_at | out_of_service_for
------------ ------------------------------- --------------------
ACX-685 | 2021-12-24 16:15:34.822808 00 | 00:00:01
BRT-162 | 2021-12-25 11:26:31.827361 00 | 00:00:27
uj5u.com熱心網友回復:
您可以使用視窗函式解決問題:
with data as (
select
*,
lead(updated_at) over (partition by vehicle_id order by updated_at) next_state
from vehicles
) select
*,
(next_state - updated_at) out_of_service_for
from data where state = 'out-of-service';
PostgreSQL 視窗函式
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/397715.html
標籤:sql PostgreSQL的
