博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
postgresql如何实现group_concat功能
阅读量:7100 次
发布时间:2019-06-28

本文共 1679 字,大约阅读时间需要 5 分钟。

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_nameFROM    product_attribute_line AS lLEFT JOIN product_attribute AS a ON l.attribute_id = a.idLEFT JOIN product_attribute_value AS v ON l.attribute_id=v.attribute_idLEFT JOIN product_attribute_price AS p ON v.id=p.value_id AND p.product_tmpl_id=197WHERE l.product_tmpl_id=197) tGROUP BY name

结果:

 

转载于:https://www.cnblogs.com/hltswd/p/5611157.html

你可能感兴趣的文章
基于FPGA的dds发生器与lcd显示参数
查看>>
HDU-6216 A Cubic number and A Cubic Number [二分]
查看>>
php单例模式的使用场景,使用方法
查看>>
fetch请求get方式以及post提交参数为formdata类型的数据
查看>>
[学习笔记]凸优化/WQS二分/带权二分
查看>>
CentOS 下 LVS集群( 可能更新 )
查看>>
差分信号(Differential Signal)
查看>>
Aix项目_shell_rsh_01
查看>>
HDU 5726 GCD 求给定序列中与查询段相等的GCD个数
查看>>
教育培训机构的信息化管理,要先从这四大业务场景做起
查看>>
[Mugeda HTML5技术教程之15]案例分析:制作移动教育课件
查看>>
揭开Socket编程的面纱
查看>>
一个结构体指针数组内存分配问题引发的思考
查看>>
主席树
查看>>
php-memcache
查看>>
MJRefresh tableview基本刷新的封装
查看>>
OpenStack视图
查看>>
有效用例模式阅读笔记一
查看>>
网络爬虫(一)
查看>>
查看Win7系统的cookies
查看>>