I have some tables from this table and I use this table to get records
string_agg(a2.sampl_no, ', ') as sampl_nosThe
and group by clauses work fine, but I want to have at most 4 sample_no aggregates per row.
Suppose I get
from the databasestring_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粉5641921312024-02-04 15:08:29
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)