Get a pair of records from group by clause
P粉195402292
P粉195402292 2024-02-04 00:15:13
0
1
475

I have some tables from this table and I use this table to get records

string_agg(a2.sampl_no, ', ') as sampl_nos
The

and group by clauses work fine, but I want to have at most 4 sample_no aggregates per row.

Suppose I get

from the database
string_agg as (0001, 0002, 0003, 0004, 0005, 0006)

In a row, but I want this

(0001, 0002, 0003, 0004) (0006, 0007).

Help me solve this problem.

P粉195402292
P粉195402292

reply all(1)
P粉564192131

If you want to do this in the database, you can use row_number() to split the records into four groups and then use string_agg():

select * from rec_agg;
┌───────────┐
│ sample_no │
├───────────┤
│ 0001      │
│ 0002      │
│ 0003      │
│ 0004      │
│ 0005      │
│ 0006      │
│ 0007      │
│ 0008      │
│ 0009      │
│ 0010      │
│ 0011      │
└───────────┘
(11 rows)


with mk_grp as (
  select *, ((row_number() over (order by sample_no)) - 1) / 4 as grp 
    from rec_agg
) 
select string_agg(sample_no, ' ,') 
  from mk_grp 
 group by grp ;
┌────────────────────────┐
│       string_agg       │
├────────────────────────┤
│ 0001 ,0002 ,0003 ,0004 │
│ 0009 ,0010 ,0011       │
│ 0005 ,0006 ,0007 ,0008 │
└────────────────────────┘
(3 rows)
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template