Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

ARRAY_AGG() grouped by another column's values

Here’s my table like below

p_no  type  name  value
------------------------
1     A     Tomy  1
1     A     Nick  2
1     B     Tomy  3
1     B     Nick  4
1     C     Tomy  5
1     C     Nick  4
2     A     Tomy  8
2     A     Nick  7
2     B     Tomy  5
2     B     Nick  4

It means each p_no represents a block that records poeple’s value in both A, B, C type (might be more types).

I want to select a person with his value of all types

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Given p_no=1, name=Tomy

A    B    C    D
------------------
1    3    5    ..

I have tried

SELECT p_no, t[1] A, t[2] B/*, t[3] C.....*/
FROM (
    SELECT p_no, ARRAY_AGG(type) FILTER (WHERE name='Tomy') t
    FROM type
    GROUP BY 1
    ORDER BY 1) _unused

but it cannnot make the ARRAY_AGG() include the value

I think I need something similar to ARRAY_AGG('value' GROUP BY 'type')

Is this kind of query possible or is there any better alternatives?

>Solution :

Your intuition is right. You want to aggregate value ordered by type, so:

select p_no, t[1] as "A", t[2] as "B", t[3] as "C"
from (
    select p_no, array_agg(value order by type) as t
    from my_table
    where name = 'Tomy' 
    group by p_no
    ) s

db<>fiddle.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading