Oracle column-to-row function Listagg()

Original: http://dacoolbaby.iteye.com/blog/1698957

This is an Oracle column-to-row function: LISTAGG()

 

Look at the sample code first:

Sql code   Favorite code
  1. with temp as(  
  2.   select 'China' nation ,'Guangzhou' city from dual union all  
  3.   select 'China' nation ,'Shanghai' city from dual union all  
  4.   select 'China' nation ,'Beijing' city from dual union all  
  5.   select 'USA' nation ,'New York' city from dual union all  
  6.   select 'USA' nation ,'Bostom' city from dual union all  
  7.   select 'Japan' nation ,'Tokyo' city from dual   
  8. )  
  9. select nation,listagg(city,',') within GROUP (order by city)  
  10. from temp  
  11. 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:

Sql code   Favorite code
  1. with temp as(  
  2.   select 500 population, 'China' nation ,'Guangzhou' city from dual union all  
  3.   select 1500 population, 'China' nation ,'Shanghai' city from dual union all  
  4.   select 500 population, 'China' nation ,'Beijing' city from dual union all  
  5.   select 1000 population, 'USA' nation ,'New York' city from dual union all  
  6.   select 500 population, 'USA' nation ,'Bostom' city from dual union all  
  7.   select 500 population, 'Japan' nation ,'Tokyo' city from dual   
  8. )  
  9. select population,  
  10.        nation,  
  11.        city,  
  12.        listagg(city,',') within GROUP (order by city) over (partition by nation) rank  
  13. from temp  

 

Summary: LISTAGG() can use it as the SUM() function.

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326217886&siteId=291194637