我有两个表:
表 1:
id | color | qty
---|-------|-----
1 | red | 10
2 | green | 20
3 | blue | 50
表 2:
id | shade
---|-------
1 | light
1 | dark
2 | light
3 | light
3 | dark
我如何编写一个查询来连接两个表并将阴影作为逗号分隔的字符串返回,即
1 | red | light, dark | 10
2 | green | light | 20
3 | blue | light, dark | 50
最佳答案
如果您使用的是 9.0 或更高版本,您可以使用带有 « string_agg » 的聚合查询:
SELECT
t1.id,
t1.color,
string_agg(t2.shade, ', ')
t1.quantity
FROM
table1 as t1
INNER JOIN table2 t2 on t2.id = t1.id
GROUP BY
t1.id,
t1.color,
t1.quantity
关于sql - 如何在连接的聚合查询中聚合字段中的多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53972919/