postgresql如何实现group_concat功能

MySQL有个聚集函数group_concat, 它可以按group的id,将字段串联起来,如

表:
id name
---------------
1 A
2 B
1 B

SELECT id, group_concat(name) from xxx group by id
得出的结果为

id group_concat(name)
---------------------------
1 A,B
2 B

PostgreSQL没有现成的group_concat聚集函数,但可以自定义聚集函数,所以可以容易的实现这功能。

自定义聚集函数 group_concat

CREATE AGGREGATE group_concat(anyelement)
(
sfunc = array_append, -- 每行的操作函数,将本行append到数组里
stype = anyarray, -- 聚集后返回数组类型
initcond = '{}' -- 初始化空数组
);

参数anyelement匹配任何类型,聚集后返回数组类型anyarray,该函数的功能是将每行的记录附加到数组里。

SELECT id, group_concat(name) from xxx group by id
得出的结果为

id array_accum(name)
---------------------------
1 {'A','B'}
2 {'B'}

array_accum(name)为数组类型,再用array_to_string函数将数组转换为字符串

SELECT id, array_to_string(group_concat(name),',') from xxx group by id
就可以得到group_concat相同的结果了。

但MySQL的group_concat的功能很强,比如可以排序等,postgresql若要模拟它,只能自己定义一个增强型的函数比如array_to_string_plus,可以对数组进行排序后再concat,这里就不用多述,留给各位动脑筋吧。

自己写的一个例子:
 
DROP AGGREGATE group_concat(anyelement);
CREATE
AGGREGATE group_concat(anyelement) ( sfunc = array_append, -- 每行的操作函数,将本行append到数组里 stype = anyarray, -- 聚集后返回数组类型 initcond = '{}' -- 初始化空数组 ); SELECT name,group_concat(t.value_id) value_id,group_concat(t.value_name) value_name,group_concat(t.price_extra) price_extra FROM( SELECT l.product_tmpl_id, a.name, p.price_extra, l.attribute_id, v.id AS value_id, v.name as value_name FROM product_attribute_line AS l LEFT JOIN product_attribute AS a ON l.attribute_id = a.id LEFT JOIN product_attribute_value AS v ON l.attribute_id=v.attribute_id LEFT JOIN product_attribute_price AS p ON v.id=p.value_id AND p.product_tmpl_id=197 WHERE l.product_tmpl_id=197) t GROUP BY name

结果:

 

posted @ 2016-06-23 16:01  屌丝IT男  阅读(3405)  评论(0)    收藏  举报