2016-08-19 93 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