I ran into this problem in PostgreSQL. I have a test table with two columns: - id and content . eg.
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.');
If I run the following query ...
select id, length(content) as characters from test order by id
... then I get: -
id | characters ---+----------- 1 | 74 2 | 55 3 | 87 4 | 26 5 | 120 6 | 85 7 | 87 8 | 35
What I want to do is group id into strings where the sum of the content exceeds the threshold value. For example, if this threshold is 100 , then the desired result will look like this: -
ids | characters ----+----------- 1,2 | 129 3,4 | 113 5 | 120 6,7 | 172 8 | 35
NOTE (1):. For the query, you do not need to generate a column of characters - only ids - they are here to report that they are 100 entirely - except for the last row, which is 35 .
NOTE (2): - ids can be a comma delimited string or a PostgreSQL array - the type is less important than the values
Can I use the window function for this, or do I need something more complex, like lateral join ?