Home  >  Q&A  >  body text

Get a pair of records from group by clause

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粉195402292P粉195402292233 days ago429

reply all(1)I'll reply

  • P粉564192131

    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)

    reply
    0
  • Cancelreply