将两行合并为一行

时间:2016-08-19 07:48:53

标签: postgresql

以下查询为我提供了两行,因为学生有两个联系人。我希望能够做的是在一行中显示两个联系人。

如果有人能够帮助我,我将非常感激。

查询

select student.code as "student code", student.firstname, student.surname, student.birth_date, contact.firstname as "contact firtname", contact.surname as "contact surname"
from 
student
join "studentContact" on student.id = "studentContact".student
join contact on "studentContact".contact = contact.id

输出

student code  firstname surname birthdate   contact firstname   contact surname
1234           John      Doe    19/09/2000  Jane                Doe 
1234           John      Doe    19/09/2000  Harry               Doe 

1 个答案:

答案 0 :(得分:3)

您可以使用string_agg功能。 像这样:

select student.code as "student code", student.firstname, student.surname, student.birth_date, string_agg(concat(contact.firstname, ' ', contact.surname), ', ') as "contacts"
from 
student
join "studentContact" on student.id = "studentContact".student
join contact on "studentContact".contact = contact.id
group by student.id