1.需求:
原始数据如下(建表sql在文章底部):
目标:根据type进行分组,把楼栋名去重后用"/"进行拼接
2.解决:
方案1:使用wm_concat
select TYPE , wm_concat(NAME) NAME from T_BUILDING group by TYPE;
wm_concat 默认使用的是逗号进行拼接,结果如下(此时NAME的结果类型为:BLOB):
再配合使用子查询和replace函数达到目的,sql如下:
select t1.TYPE , replace(wm_concat(t1.NAME),',','/') NAME from (select distinct TYPE,NAME from T_BUILDING) t1 group by t1.TYPE;
结果如下:
方案2:使用listagg
select t1.TYPE , listagg(t1.NAME,'/') WITHIN GROUP( ORDER BY t1.NAME) NAME from (select distinct TYPE,NAME from T_BUILDING) t1 group by t1.TYPE;
结果如下(此时NAME的结果类型为:VARCHAR):
附:表数据sql脚本如下:
create table T_BUILDING
(
ID NUMBER not null
constraint T_BUILDING_PK
primary key,
NAME VARCHAR2(200),
TYPE NUMBER
)
/
comment on column T_BUILDING.NAME is '楼栋名'
/
comment on column T_BUILDING.TYPE is '类型'
/
INSERT INTO SCOTT.T_BUILDING (ID, NAME, TYPE) VALUES (1, '楼栋1', 1);
INSERT INTO SCOTT.T_BUILDING (ID, NAME, TYPE) VALUES (2, '楼栋2', 1);
INSERT INTO SCOTT.T_BUILDING (ID, NAME, TYPE) VALUES (3, '楼栋1', 1);
INSERT INTO SCOTT.T_BUILDING (ID, NAME, TYPE) VALUES (4, '楼栋11', 2);
INSERT INTO SCOTT.T_BUILDING (ID, NAME, TYPE) VALUES (5, '楼栋22', 2);