如何编写此Postgres查询?

时间:2018-09-21 16:06:26

标签: sql postgresql rank gaps-and-islands

对于我的数据,我有一个在1到0之间切换的值。我需要找到值为0的分段的“时间增量”。我认为这将使用min(),max()函数。可能排名。

输入:

Time_stamp            , value
'2018-01-01 10:15:00' , 1
'2018-01-01 10:16:00' , 1
'2018-01-01 10:17:00' , 0
'2018-01-04 10:18:00' , 0
'2018-01-04 10:19:00' , 1
'2018-01-04 10:20:00' , 1
'2018-01-06 10:21:00' , 1
'2018-01-06 10:22:00' , 0
'2018-01-06 10:23:00' , 0
'2018-01-07 10:24:00' , 1
'2018-01-07 10:25:00' , 1
'2018-01-07 10:26:00' , 1


Output
id | max                  |  min  
1  |'2018-01-04 10:18 AM' |'2018-01-01 10:17 AM'
2  |'2018-01-06 10:23 AM' |'2018-01-06 10:22 AM'

这是创建数据的SQL

CREATE TABLE test_ts (
    time_stamp     TIMESTAMPTZ,
    val    integer
);
insert into test_ts
SELECT * FROM (
 VALUES
  ( '2018-01-01 10:15:00'::timestamptz , 1),
   ( '2018-01-01 10:16:00'::timestamptz  , 1),
   ( '2018-01-01 10:17:00'::timestamptz  , 0),
   ( '2018-01-04 10:18:00'::timestamptz  , 0),
   ( '2018-01-04 10:19:00'::timestamptz  , 1),
   ( '2018-01-04 10:20:00'::timestamptz  , 1),
   ( '2018-01-06 10:21:00'::timestamptz  , 1),
   ( '2018-01-06 10:22:00'::timestamptz  , 0),
   ( '2018-01-06 10:23:00'::timestamptz  , 0),
   ( '2018-01-07 10:24:00'::timestamptz  , 1),
   ( '2018-01-07 10:25:00'::timestamptz  , 1),
   ( '2018-01-07 10:26:00'::timestamptz  , 1)) testAlias;

1 个答案:

答案 0 :(得分:4)

这是一个所谓的缺口和孤岛问题。使用两个计数器,一个用于所有行,一个用于每个值,然后减去,您将获得每个值的组键:

select max(time_stamp), min(time_stamp)
from
(
  select 
    time_stamp,
    val,
    row_number() over (order by time_stamp) -
    row_number() over (partition by val order by time_stamp) as grp
  from test_ts
) groups
where val = 0
group by grp
order by min(time_stamp);

上个月的演示:http://rextester.com/WIUX68902