Listagg(): column rollover function


Classification:
Oracle(67)

This is an Oracle column conversion function: listag()

Oracle after version 11.2 can be used, but the previous version cannot be used, and an error will be reported.

First look at the sample 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 an aggregate function. Through the Group by statement, one field of each Group is spliced.

Very convenient.

 

It is also an aggregate function, with an advanced usage:

over(partition by XXX)

In other words, when you are not using the Group by statement, you can also use the listag function:

  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  

Keywords: Oracle

Added by mkoga on Sun, 05 Apr 2020 11:31:22 +0300