如何使用窗口函数枚举Postgres表中的分区组?

时间:2018-08-23 14:33:09

标签: sql postgresql partitioning window-functions

假设我有一个这样的表:

id  | part  | value
----+-------+-------
 1  | 0     | 8
 2  | 0     | 3
 3  | 0     | 4
 4  | 1     | 6
 5  | 0     | 13
 6  | 0     | 4
 7  | 1     | 2
 8  | 0     | 11
 9  | 0     | 15
 10 | 0     | 3
 11 | 0     | 2

我想枚举属性为1的行之间的组。

所以我想得到这个:

id  | part  | value | number
----+-------+-----------------
 1  | 0     | 8     |   1
 2  | 0     | 3     |   1
 3  | 0     | 4     |   1
 4  | 1     | 6     |   0
 5  | 0     | 13    |   2
 6  | 0     | 4     |   2
 7  | 1     | 2     |   0
 8  | 0     | 11    |   3
 9  | 0     | 15    |   3
 10 | 0     | 3     |   3
 11 | 0     | 2     |   3

是否可以使用Postgres窗口函数来实现此目的,或者还有其他方法吗?

2 个答案:

答案 0 :(得分:2)

您似乎想要比零件的累加总和多1的东西。最简单的方法是:

select t.*,
       (case when part = 1 then 0  -- the easy case
             else 1 + sum(part) over (order by id)
        end) as number
from t;

如果part可以采用0和1以外的值,则

select t.*,
       (case when part = 1 then 0  -- the easy case
             else 1 + sum( (part = 1)::int ) over (order by id)
        end) as number
from t;

答案 1 :(得分:1)

如果我正确理解,则需要类似的东西:

with t(id  , part  , value) as(
values
(1  , 0     , 8),
(2  , 0     , 3),
(3  , 0     , 4),
(4  , 1     , 6),
(5  , 0     , 13),
(6  , 0     , 4),
(7  , 1     , 2),
(8  , 0     , 11),
(9  , 0     , 15),
(10 , 0     , 3),
(11 , 0     , 2)
)

select id, part, value, case when  part = 1 then 0 else dense_rank() over(order by grp) end as result
from (
    select *,
    row_number() over(order  by id)   -
    row_number() over(partition by part order  by id) as grp
    from t
    order by id
) tt
order by id