How to enumerate groups of partitions in my Postgres table with window functions?

て烟熏妆下的殇ゞ 提交于 2019-12-11 12:45:50

问题


Suppose I have a table like this:

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

I would like to enumerate groups between rows that have part atribute 1.

So I would like to get this:

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

Is it possible to achieve this with Postgres window functions or is there any other way?


回答1:


You seem to want something like 1 more than the cumulative sum of the parts. The simplest method is:

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

If part can take on values other than 0 and 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;



回答2:


If i correctly understand, you need something like:

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


来源:https://stackoverflow.com/questions/51988259/how-to-enumerate-groups-of-partitions-in-my-postgres-table-with-window-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!