Look at the sample code first:
SQL code
- With temp as (
- Select ' China ' nation,' Guangzhou ' to dual Union All
- Select ' China ' nation,' Shanghai ' to dual Union All
- Select ' China ' Nation,' Beijing ' to dual Union All
- Select ' USA ' Nation,' New York ' to dual Union all
- Select ' USA ' Nation,' Bostom ' city from dual Union All
- Select ' Japan ' Nation,' Tokyo ' 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)
Using a GROUP BY statement, a field of each group is stitched together, just like an aggregate function.
Very convenient.
Also an aggregation function, there is an advanced usage:
Is over (partition by XXX)
In other words, you can also use the Listagg function when you are not practical with the GROUP BY statement:
SQL code
- With temp as (
- Select population, ' China ' nation,' Guangzhou ' to dual Union All /c1>
- Select population, ' China ' nation,' Shanghai ' to dual Union all
- Select population, ' China ' Nation,' Beijing ' to dual Union all
- Select population, ' USA ' Nation,' New York ' city from dual Union all
- Select population, ' USA ' Nation,' Bostom ' city from dual Union all
- Select 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 () uses it as a sum () function.
Turn: Oracle's Column change function: Listagg ()