Original: http://dacoolbaby.iteye.com/blog/1698957
This is an Oracle column-to-row function: LISTAGG()
Look at the sample code first:
- with temp as(
- select 'China' nation ,'Guangzhou' city from dual union all
- select 'China' nation ,'Shanghai' city from dual union all
- select 'China' nation ,'Beijing' city from dual union all
- select 'USA' nation ,'New York' city from dual union all
- select 'USA' nation ,'Bostom' city from dual union all
- select 'Japan' nation ,'Tokyo' city from dual
- )
- select nation,listagg(city,',') within GROUP (order by city)
- from temp
- group by nation
This is the most basic usage:
LISTAGG(XXX,XXX) WITHIN GROUP( ORDER BY XXX)
The usage is like the aggregation function, through the Group by statement, a field of each Group is spliced together.
Very convenient.
It is also an aggregate function, and there is an advanced usage:
is over(partition by XXX)
That is to say, you can also use the LISTAGG function when you do not use the Group by statement:
- with temp as(
- select 500 population, 'China' nation ,'Guangzhou' city from dual union all
- select 1500 population, 'China' nation ,'Shanghai' city from dual union all
- select 500 population, 'China' nation ,'Beijing' city from dual union all
- select 1000 population, 'USA' nation ,'New York' city from dual union all
- select 500 population, 'USA' nation ,'Bostom' city from dual union all
- select 500 population, 'Japan' nation ,'Tokyo' city from dual
- )
- select population,
- nation,
- city,
- listagg(city,',') within GROUP (order by city) over (partition by nation) rank
- from temp
Summary: LISTAGG() can use it as the SUM() function.