Postgresql GROUP_CONCAT 에 해당?
-
23-09-2019 - |
문제
나는 테이블과 싶을 끌어당 하나의 행 id 필드 값으로 연결됩니다.
내 테이블,예를 들어,내가 이:
TM67 | 4 | 32556
TM67 | 9 | 98200
TM67 | 72 | 22300
TM99 | 2 | 23009
TM99 | 3 | 11200
그리고 나는 다음과 같이 출력:
TM67 | 4,9,72 | 32556,98200,22300
TM99 | 2,3 | 23009,11200
MySQL 할 수 있었을 사용하여 집계 기능 GROUP_CONCAT
, 지만,작동하지 않는 것 같이 여기...은 거기에 해당하는 PostgreSQL,또는 다른 방법으로 수행하는 이?
해결책
This is probably a good starting point (version 8.4+ only):
SELECT id_field, array_agg(value_field1), array_agg(value_field2)
FROM data_table
GROUP BY id_field
array_agg returns an array, but you can CAST that to text and edit as needed (see clarifications, below).
Prior to version 8.4, you have to define it yourself prior to use:
CREATE AGGREGATE array_agg (anyelement)
(
sfunc = array_append,
stype = anyarray,
initcond = '{}'
);
(paraphrased from the PostgreSQL documentation)
Clarifications:
- The result of casting an array to text is that the resulting string starts and ends with curly braces. Those braces need to be removed by some method, if they are not desired.
- Casting ANYARRAY to TEXT best simulates CSV output as elements that contain embedded commas are double-quoted in the output in standard CSV style. Neither array_to_string() or string_agg() (the "group_concat" function added in 9.1) quote strings with embedded commas, resulting in an incorrect number of elements in the resulting list.
- The new 9.1 string_agg() function does NOT cast the inner results to TEXT first. So "string_agg(value_field)" would generate an error if value_field is an integer. "string_agg(value_field::text)" would be required. The array_agg() method requires only one cast after the aggregation (rather than a cast per value).
다른 팁
Since 9.0 this is even easier:
SELECT id,
string_agg(some_column, ',')
FROM the_table
GROUP BY id
SELECT array_to_string(array(SELECT a FROM b),', ');
을 할 것입니다.
Try like this:
select field1, array_to_string(array_agg(field2), ',')
from table1
group by field1;
and the version to work on the array type:
select
array_to_string(
array(select distinct unnest(zip_codes) from table),
', '
);
My sugestion in postgresql
SELECT cpf || ';' || nome || ';' || telefone
FROM (
SELECT cpf
,nome
,STRING_AGG(CONCAT_WS( ';' , DDD_1, TELEFONE_1),';') AS telefone
FROM (
SELECT DISTINCT *
FROM temp_bd
ORDER BY cpf DESC ) AS y
GROUP BY 1,2 ) AS x
제휴하지 않습니다 StackOverflow