我有表:
Project table id name ------- 1 A 2 B Assignment table id name project_id ------------------- 1 A1 1 2 A2 1 3 A3 2
我希望编写一个查询,以返回每个项目以及从中创建的分配名称的查询,例如:
project_id assignments ----------------------- 1 A1,A2 2 A3
有什么办法可以实现?
您可以联接表并用于array_agg合并用逗号分隔的值
array_agg
SELECT a.id, array_agg(b.name) assignments FROM Project a INNER JOIN assignment b ON a.id = b.project_ID GROUP BY a.id
或使用 STRING_AGG
STRING_AGG
SELECT a.id, STRING_AGG(b.name, ', ' ORDER BY b.name) assignments FROM Project a INNER JOIN assignment b ON a.id = b.project_ID GROUP BY a.id