group_concat on postgresql

前端之家收集整理的这篇文章主要介绍了group_concat on postgresql前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
CREATE TABLE produk
(
seq_id serial NOT NULL,name character varying(100) NOT NULL
) ;

INSERT INTO produk (seq_id,name) VALUES (1,'beer');
INSERT INTO produk (seq_id,name) VALUES (2,'in');
INSERT INTO produk (seq_id,name) VALUES (3,name) VALUES (4,'can');
INSERT INTO produk (seq_id,name) VALUES (6,'goods');
INSERT INTO produk (seq_id,name) VALUES (7,name) VALUES (8,name) VALUES (5,'goods');

MysqL:

select name,group_concat(cast(seq_id as char)) as id_of_duplicates
from produk
group by name
order by name;


Postgresql:

create aggregate array_accum (
sfunc = array_append,basetype = anyelement,stype = anyarray,initcond = '{}'
);

CREATE OR REPLACE FUNCTION _group_concat(text,text)
RETURNS text AS $$
SELECT CASE
WHEN $2 IS NULL THEN $1
WHEN $1 IS NULL THEN $2
ELSE $1 operator(pg_catalog.||) ',' operator(pg_catalog.||) $2
END
$$ IMMUTABLE LANGUAGE sql;

CREATE AGGREGATE group_concat (
BASETYPE = text,SFUNC = _group_concat,STYPE = text
);


first approach:

select name,array_accum(seq_id)
from produk
group by name

select name,array_to_string(array_accum(seq_id),',')
from produk
group by name;


second approach (MysqL-compatible approach):

select name,group_concat(seq_id) as id_of_duplicates
from produk
group by name
order by name;


MysqL GROUP_CONCAT with ordering:

select name,group_concat(cast(seq_id as char) order by seq_id) as id_of_duplicates
from produk
group by name
order by name;


Postgresql equivalent:

select name,group_concat(distinct seq_id) as id_of_duplicates
from produk
group by name
order by name;


using customized sort:

select name,group_concat(seq_id) as id_of_duplicates
from
(
select name,seq_id
from produk
order by name,seq_id
) as x
group by name


http://s2.diffuse.it/blog/show/10-group_concat_on_postgresql

原文链接:https://www.f2er.com/postgresql/196615.html

猜你在找的Postgre SQL相关文章