PostgreSQL怎么实现分类汇总?
我们首先创建一个测试表,并插入一些测试数据:
create table test(id int,name varchar(100));
insert into test values(1,'aa');
insert into test values(1,'bb');
insert into test values(2,'cc');
insert into test values(3,'dd');
insert into test values(2,'ff');
1。
使用数组函数两组内的列表转换成数组
select id,array_to_string(
array(select name from test where id=a。id),',')
from test a
group by id;
--结果
3 | dd
2 | cc,ff
1 | aa,bb
是不是看起来非常的简单呢,呵呵,非常的cool!
2。
使用自定义的聚集函数
PostgreSQL除了提供给我们的一些预定义函数之外,还有创建聚集函数的DDL语句,非常的灵活!
--首先创建一个状态传递函数:实现将统计结果传递连接
create function pg_concat( text, text ) returns text as '
begin
if $1 isnull then
return $2;
else
return $1 || $2;
end if;
end;' language 'plpgsql';
--创建一个最终的结果函数:实现将最后一个连接符号清除
create function pg_concat_fin(text) returns text as '
begin
return substr($1,1,length($1)-1);
end;' language 'plpgsql';
--创建聚集函数,入口参数basetype:text,状态传递函数:pg_concat,状态变量类型:text,结果函数finalfunc:pg_concat_fin
create aggregate pg_concat (
basetype = text,
sfunc = pg_concat,
stype = text,
finalfunc = pg_concat_fin);
--使用聚集函数进行统计:
select id,pg_concat(name||',')
from test
group by id;
--结果
3 | dd
2 | cc,ff
1 | aa,bb
和第一种方法得到的结果是一样的,非常的方便。