Enumerating table partitions in Postgres table

风格不统一 提交于 2019-12-11 03:33:59

问题


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 that have part atribute 0.

Ultimately I want to get this:

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

Is it possible to solve this with Postgres window functions or is there another way?


回答1:


Yes, that is simple:

SELECT id, part, value,
       row_number() OVER (PARTITION BY grp ORDER BY id) - 1 AS number
FROM (SELECT id, part, value,
             sum(part) OVER (ORDER BY id) AS grp
      FROM mytable
     ) AS q;

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


来源:https://stackoverflow.com/questions/51984611/enumerating-table-partitions-in-postgres-table

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