GROUP BY
查询中连接字符串?问题:
在 PostgreSQL 中,如何在 GROUP BY
查询中连接字段的字符串?
示例:
考虑一个具有以下模式的表:
ID | COMPANY_ID | EMPLOYEE |
---|---|---|
1 | 1 | Anna |
2 | 1 | Bill |
3 | 2 | Carol |
4 | 2 | Dave |
目标是按 COMPANY_ID
分组并连接 EMPLOYEE
值,结果如下:
COMPANY_ID | EMPLOYEE |
---|---|
1 | Anna, Bill |
2 | Carol, Dave |
解决方案:
PostgreSQL 9.0 或更高版本:
string_agg(expression, delimiter)
函数:<code class="language-sql">SELECT company_id, string_agg(employee, ', ') FROM mytable GROUP BY company_id;</code>
PostgreSQL 8.4.x:
array_agg(expression)
函数结合 array_to_string()
:<code class="language-sql">SELECT company_id, array_to_string(array_agg(employee), ', ') FROM mytable GROUP BY company_id;</code>
PostgreSQL 8.3.x 及更早版本:
<code class="language-sql">CREATE AGGREGATE textcat_all( basetype = text, sfunc = textcat, stype = text, initcond = '' ); SELECT company_id, textcat_all(employee) FROM mytable GROUP BY company_id;</code>
以上是如何在 PostgreSQL GROUP BY 查询中连接字符串?的详细内容。更多信息请关注PHP中文网其他相关文章!