2016-08-19 106 views
2

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

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

查询

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 

回答

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 
+0

这里假设'id'是table'student'的主键。考虑到加入条件,最有可能是一个有效的假设,但值得一提。 – Patrick