我有下表:
- table1 id, user_id, first_name, last_name
- table2 id, user_id, company_name, first_name, last_name, partner_id
- 表 3 企业 ID、企业名称
我想创建将返回数据行的查询: user_id, (first_name last_name), (business_name, business_name ...) 当用户与多个企业相关联时,是这样的: 123、李四,业务 1,业务 2
当我使用以下查询时,我会得到一些重复的行:
SELECT table1.first_name, table1.last_name, table2.copmany_name,
(case when concat(table1.first_name, table1.last_name) = '' then table2.company_name else concat_ws(' ', table1.first_name,table1.last_name) end) as name,
table3.name as business_name
FROM table1
JOIN table2 ON table1.user_id = table2.user_id
JOIN table3 ON table2.partner_id = table3.id
这是该查询的示例:
123, John Doe, Business1
123, John Doe, Business2
125, Marie Bird, Business3
我想得到:
123, John Doe, Business1, Business2
125, Marie Bird, Business3
这可能吗?
谢谢
最佳答案
您可以使用 array_agg在 postgresql.Aggregate 函数中从一组输入值计算单个结果。:
SELECT table1.first_name, table1.last_name, table2.copmany_name,
(case when concat(table1.first_name, table1.last_name) = '' then table2.company_name else concat_ws(' ', table1.first_name,table1.last_name) end) as name,
array_agg(table3.name) as business_name
FROM table1
JOIN table2 ON table1.user_id = table2.user_id
JOIN table3 ON table2.partner_id = table3.id
关于sql - postgresql如何连接多个表以获得逗号分隔的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34500395/