sql - 如何按不间断序列对条目进行分组?

标签 sql postgresql gaps-and-islands

CREATE TABLE entries (
  id serial NOT NULL,
  title character varying,
  load_sequence integer
);

和数据

INSERT INTO entries(title, load_sequence) VALUES ('A', 1);
INSERT INTO entries(title, load_sequence) VALUES ('A', 2);
INSERT INTO entries(title, load_sequence) VALUES ('A', 3);

INSERT INTO entries(title, load_sequence) VALUES ('A', 6);

INSERT INTO entries(title, load_sequence) VALUES ('B', 4);
INSERT INTO entries(title, load_sequence) VALUES ('B', 5);

INSERT INTO entries(title, load_sequence) VALUES ('B', 7);
INSERT INTO entries(title, load_sequence) VALUES ('B', 8);

在 PostgreSQL 中有没有一种方法可以编写 SQL,在按 load_sequence 对数据进行排序后,按相同的 title 段对数据进行分组。 我的意思是:

=# SELECT id, title, load_sequence FROM entries ORDER BY load_sequence;
 id | title | load_sequence 
----+-------+---------------
  9 | A     |             1
 10 | A     |             2
 11 | A     |             3
 13 | B     |             4
 14 | B     |             5
 12 | A     |             6
 15 | B     |             7
 16 | B     |             8

我想要群组:

=# SELECT title, string_agg(id::text, ',' ORDER BY id) FROM entries ???????????;

所以结果是:

 title | string_agg  
-------+-------------
 A     | 9,10,11
 B     | 13,14
 A     | 12
 B     | 15,16

最佳答案

您可以使用以下查询:

SELECT title, string_agg(id::text, ',' ORDER BY id)
FROM (
  SELECT id, title, 
         ROW_NUMBER() OVER (ORDER BY load_sequence) -
         ROW_NUMBER() OVER (PARTITION BY title 
                            ORDER BY load_sequence) AS grp
  FROM entries ) AS t
GROUP BY title, grp

计算的 grp 字段用于识别具有连续 load_sequence 值的 title 记录片段。在 GROUP BY 子句中使用此字段,我们可以实现对 id 值的所需聚合。

Demo here

关于sql - 如何按不间断序列对条目进行分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32349859/

相关文章:

java - Hibernate 延迟加载不适用于多对一映射

SQL Server 存储过程 select top 1 并在一条语句中更新?

java - 是否可以将 PostgreSQL 中的字符字段转换为 JPA 命名查询中的整数?

postgresql - 显示特定用户拥有的所有表的命令

sql - PostgreSQL array_agg 但有停止条件

sql - 从具有排名契约(Contract)的日期创建历史表(差距和孤岛?)

java - ORA-12704 : character set mismatch when performing multi-row INSERT of nullable NVARCHAR's

mysql外连接在哪里

node.js - 使用 nodejs sequelize pg.js "the dialect postgres is not supported"连接到 postgres 数据库时出错

sql - 如何在 T-SQL 中根据前几个月的数据确定缺失月份的值