简体   繁体   中英

How canI aggregate and group in two columns?

   Name          age   gender
competition1      3      0
competition1      3      1
competition1      2      0
competition1      2      1
competition2      3      0
competition2      3      1
competition3      1      0

I want to query in this table that convert in below table.

     Name          Array of ages   Array of gender
'competition1',      {'3','2'}       {'0','1'}
'competition2',      {'3'}       {'0','1'}
'competition3',      {'1'}           {'0'}

You can aggregate by name , and use array_agg(distinct...) to generate arrays without duplicates. Note that you can also order the values in the arrays as needed:

select 
    name, 
    array_agg(distinct age order by age desc) ages, 
    array_agg(distinct gender order by gender) genders
from mytable
group by name

You could use array_agg

 SELECT name, array_agg(age), array_agg(gender)
 FROM data_table
 GROUP BY name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM