假如有员工表(t_employee)包含:部门ID、姓名、年龄
需求:将同一部门的员工姓名按年龄从小到大的顺序拼接起来,一个部门一行
表中数据如下:
depID | name | age |
1 | messi | 27 |
1 | avatar | 26 |
2 | louis | 25 |
2 | victoria | 24 |
sql语句:
select b.depID, max(b.names) from (select a.depID, wmsys.wm_concat(a.name) over(partition by a.depID order by a.age) names from t_employee a) b group by b.depID
查询结果为:
depID | names |
1 | avatar,messi |
2 | victoria,louis |
连接时默认用逗号分隔,若要修改为‘-’可用
replace(wmsys.wm_concat(a.name),',','-')
附上两篇相关文章:
1、开窗函数over(partition by)介绍:
2、oracle中WMSYS.WM_CONCAT函数的版本差异: