oracle 行转列 不聚合,列转行聚合的简单实现ORACLE WM_CONCAT LISTAGG函数

列转行聚合的简单实现ORACLE WM_CONCAT LISTAGG函数

项目中有个需求,将关联出来的数据以特定的字段将其他某一自动聚合。例子如下:

1    B1

1    B2

1    B3

2    B4

2    B5

3    B6

to

1    B1,B2,B3

2    B4,B5

3    B6

拿到手就想到用存储过程,其实还有更简单的方式。那就是oracle 提供的字符串聚合函数。

WM_CONCAT Built-in Function (Not Supported)

If you are not running 11g Release 2, but are running a version of the database where the WM_CONCAT function is present, then it is a zero effort solution as it performs the aggregation for you. It is actually an example of a user defined aggregate function described below, but  have done all the work for you.

LISTAGG Analystic Function in 11g Release 2

The LISTAGG analytic function was introduced in Oracle 11g Release 2, making it very easy to aggregate strings. The nice thing about this function is it also allows us to order the elements in the concatenated list. If you are using 11g Release 2 you should use this function for string aggregation.

Example 如下:

CREATE TABLE  "TESTAGG"

(

"A" VARCHAR2(20 BYTE),

"B" VARCHAR2(20 BYTE)

)

INSERT INTO "TESTAGG" (A, B) VALUES ('1', 'B1')

INSERT INTO "TESTAGG" (A, B) VALUES ('1', 'B2')

INSERT INTO "TESTAGG" (A, B) VALUES ('1', 'B3')

INSERT INTO "TESTAGG" (A, B) VALUES ('2', 'B4')

INSERT INTO "TESTAGG" (A, B) VALUES ('2', 'B5')

INSERT INTO "TESTAGG" (A, B) VALUES ('3', 'B6')

select * from testAgg

1    B1

1    B2

1    B3

2    B4

2    B5

3    B6

select  a  ,wm_concat (b) as policinams from testagg  group by a order by a

select  a ,LISTAGG(b,',' ) within group(order by a) as b from testagg group by

1    B1,B2,B3

2    B4,B5

3    B6

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值