Postgres to fetch the list having comma separated values

自作多情 提交于 2020-06-01 05:15:09

问题


I am working on Postgres SQL and having below join query, when I execute this query I get two or 3 records for each employee, because each employee has 3 different types of email address 1) Home Address 2) Office address 3) social address.

select * from root.employee c
full outer join root.employee_email ce
on c.employee_id = ce.employee_id
order by c.employee_id limit 1000 offset 0;

What I want is that employee_email.email column to give the comma separated value in the output, how can we do that ?

Note: I've almost 1 million records in DB and will use Spring Batch to migrate data from Postgres to MongoDB. The same I would need to do for Phone


回答1:


Aggregate by employee and use string_agg:

select
    c.employee_id,         -- or just c.* assuming employee_id is a PK
    string_agg(ce.email, ',') as emails
from root.employee c
full outer join root.employee_email ce
    on c.employee_id = ce.employee_id
group by
    c.employee_id
order by
    c.employee_id
limit 1000
offset 0;


来源:https://stackoverflow.com/questions/61848881/postgres-to-fetch-the-list-having-comma-separated-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!