postgresql如何实现group_concat功能
2016-06-23 16:01
621 查看
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
结果:
相关文章推荐
- 安装SQL S 4000 erver 2012 出现 Error code 0x858C001B报错
- MySQL性能调优与架构设计——第 16 章 MySQL Cluster
- 一些mysql相关测试
- innodb缓冲池
- SQL 2014 AlwaysOn 搭建
- 详解清除MongoDB所占用的多余的磁盘空间的方法
- oracle 安装步骤 登录 导入表 详细步骤
- JFinal对oracle数据库的操作配置
- sql server charindex函数和patindex函数详解(转)
- Mysql 报Row size too large 65535 的原因及解决方法
- Oracle 角色、权限
- VC中使用ADO开发数据库应用程序简明教程
- SpringMVC+Hibernate将连接oracle的数据库换成MySQL,报错如何解决
- 数据库查询
- sql server的一些常用 sql 语句
- MongoDB使用自带的命令行工具进行备份和恢复的教程
- Django数据库设计中字段为空的方式
- 一个字段多个记录拼接和多个字段的拼接
- 解决MySQL安装重装时出现could not start the service mysql error:0问题的方法
- MongoDb基本操作