【发布时间】:2016-11-09 12:16:03
【问题描述】:
我一直在 PostgreSQL 中对这个问题摸不着头脑。我有一张表test,有两列:-id 和content。例如
create table test (id integer,
content varchar(1024));
insert into test (id, content) values
(1, 'Lorem Ipsum is simply dummy text of the printing and typesetting industry.'),
(2, 'Lorem Ipsum has been the industrys standard dummy text '),
(3, 'ever since the 1500s, when an unknown printer took a galley of type and scrambled it to'),
(4, 'make a type specimen book.'),
(5, 'It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.'),
(6, 'It was popularised in the 1960s with the release of Letraset sheets containing Lorem '),
(7, 'Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker'),
(8, ' including versions of Lorem Ipsum.');
如果我运行以下查询...
select id, length(content) as characters from test order by id
...然后我得到:-
id | characters
---+-----------
1 | 74
2 | 55
3 | 87
4 | 26
5 | 120
6 | 85
7 | 87
8 | 35
我想要做的是将id 分组到内容总和超过阈值的行中。例如,如果该阈值是100,那么所需的结果将如下所示:-
ids | characters
----+-----------
1,2 | 129
3,4 | 113
5 | 120
6,7 | 172
8 | 35
注意 (1): - 查询不需要生成 characters 列 - 只需生成 ids - 他们在这里传达他们已经结束了@ 987654332@ - 除了最后一行是35。
注意 (2): - ids 可以是逗号分隔的字符串或 PostgreSQL 数组 - 类型不如值重要
我可以使用窗口函数来执行此操作还是需要更复杂的东西,例如lateral join?
【问题讨论】:
-
您的问题的答案是您需要更复杂的东西:递归 CTE。性能不会特别好。
-
我接受了@Abelisto 的答案,因为这是我在代码中使用的答案。
-
然而,@Gordon 的回答给我留下了深刻的印象,因为我通过尝试理解它学到了很多东西。谢谢大家!
标签: sql postgresql