原文:http://dacoolbaby.iteye.com/blog/1698957
这是一个Oracle的列转行函数:LISTAGG()
先看示例代码:
- withtempas(
- select'China'nation,'Guangzhou'cityfromdualunionall
- select'China'nation,'Shanghai'cityfromdualunionall
- select'China'nation,'Beijing'cityfromdualunionall
- select'USA'nation,'NewYork'cityfromdualunionall
- select'USA'nation,'Bostom'cityfromdualunionall
- select'Japan'nation,'Tokyo'cityfromdual
- )
- selectnation,listagg(city,',')withinGROUP(orderbycity)
- fromtemp
- groupbynation
这是最基础的用法:
LISTAGG(XXX,XXX) WITHIN GROUP( ORDER BY XXX)
用法就像聚合函数一样,通过Group by语句,把每个Group的一个字段,拼接起来。
非常方便。
就是over(partition by XXX)
也就是说,在你不实用Group by语句时候,也可以使用LISTAGG函数:
- withtempas(
- select500population,'China'nation,'Guangzhou'cityfromdualunionall
- select1500population,'Shanghai'cityfromdualunionall
- select500population,'Beijing'cityfromdualunionall
- select1000population,'USA'nation,'NewYork'cityfromdualunionall
- select500population,'Bostom'cityfromdualunionall
- select500population,'Japan'nation,'Tokyo'cityfromdual
- )
- selectpopulation,
- nation,
- city,
- listagg(city,')withinGROUP(orderbycity)over(partitionbynation)rank
- fromtemp
总结:LISTAGG()把它当作SUM()函数来使用就可以了。