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

标签 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 窗口函数来实现这一点,或者有其他方法吗?

最佳答案

您似乎想要比各部分的总和多 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;

关于sql - 如何使用窗口函数枚举我的 Postgres 表中的分区组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51988259/

相关文章:

php - 无法连接: Access denied for user 'indysoft_admin' @'localhost

Mysql如何进行左连接、分组并仅计算唯一的左列行

sql - Postgresql - 将整行作为数组返回

scala - 如何按每个元素的属性对列表进行分区

mysql - 向已经 HASH 分区的表添加额外的 HASH 分区

SQL SELECT If (a ="") then 更改 b 值

mysql - 如何发现MySQL存储过程的问题?

sql - 更新 postgresql 中的列

php - 无法在 mac 上退出 PSQL (`which psql` 转到 `/usr/local/php5/bin/psql` )这很奇怪

ubuntu - 无法为此处文档 : No space left on device 创建临时文件