有条件地从多行计算持续时间

时间:2019-06-26 20:57:27

标签: sql postgresql

如果我在PostgreSQL 10.5中有一个带有以下条目的表session_logs

id recorded_at          powered  camera_blocked
----------------------------------------------------
1  2019-06-26 13:40:00  true     false
2  2019-06-26 13:45:00  false    false
3  2019-06-26 13:50:00  false    true
4  2019-06-26 13:55:00  false    false
5  2019-06-26 14:00:00  true     false
6  2019-06-26 14:05:00  true     false

我想编写一个查询,该查询将给我以下结果

started_at           ended_at            power_dur battery_dur camera_blocked_dur
--------------------------------------------------------------------------------------
2019-06-26 13:40:00 2019-06-26 13:55:00  10        15          5

(持续时间(dur)以分钟为单位)

如何编写可以正确求和这些值的查询?

1 个答案:

答案 0 :(得分:1)

您可以使用lead()和条件聚合

select min(recorded_at), max(recorded_at),
       sum(next_recorded_at - recorded_at) filter (where powered),
       sum(next_recorded_at - recorded_at) filter (where camera_blocked)
from (select t.*,
             lead(recorded_at) over (order by recorded_at) as next_recorded_at
      from t
     ) t