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中文網其他相關文章!