admin管理员组文章数量:1529450
目录
- pgsql中的string_agg的用法
- String_agg基础用法介绍
- 引申用法-----string_agg排序
- 引申用法-----array_agg
- 引申用法-----array_agg 去重与排序
- contact_ws基础用法介绍
pgsql中的string_agg的用法
在之前的工作中有这么一项需求需要将数据库中两个字段合在一起展示并要求按照其中一个字段的特定顺序显示,想要做的精简一些就想在sql中完成这些功能,由此用到了string_agg,在此介绍下string_agg的所有用法.`
String_agg基础用法介绍
1.select id, string_agg(name, ‘,’) from A group by id;
id | string_agg
--------+--------------
20 | 22
30 | 33,11
此处可看出string_agg的表达式:string_agg(expression, delimiter),可理解为将一个表达式转换为字符串,上述例子为标准用法(查询同一id的name并合并起来)
引申用法-----string_agg排序
select id, string_agg(name, ','order by name asc) from A group by id;
在上述例子中若想按照name的顺序排序的话就用上面的这种形式来写,效果如下
id | string_agg
--------+--------------
20 | 22
30 | 11,33
引申用法-----array_agg
第一个例子中若换成array_agg的方式来写的话应改成:
select id, array_to_string(array_agg(name),’,’) from A group by id;
由此能看出array_agg是把表达式变成一个数组,一般来说会配合array_to_string() 函数使用
引申用法-----array_agg 去重与排序
在例子中的id可以用array_agg来进行去重和去重排序,写法分别如下:
1.select array_agg(distinct id) from A;
array_agg
----+-------
{20,30}
(1 row)
2.select array_agg(distinct id order by id desc) from A;
array_agg
----+-------
{30,20}
(1 row)
contact_ws基础用法介绍
在平时学习或者工作中难免会想让两个字段合在一起进行排序,这个时候就需要用到contact_ws这个函数,例子:
select a,b,concat_ws( ‘;’, a, b ) from A order by concat_ws( ‘;’, a, b )
a | b | concat_ws
--------+--------------
1 | 2 | 1;2
3 | 4 | 3;4
需要注意,用concat_ws函数的话是先比较第一个,再比较第二个,按顺序比较
,第一个’'中可以放任何字符
版权声明:本文标题:黄小水的sql进阶之路之postgresql中的String_agg与contact_ws 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://m.elefans.com/dongtai/1726641619a1079708.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论