Oracle列转行函数LISTAGG() WITHIN GROUP ()的使用方法

      前言:最近在写一些比较复杂的SQL,是一些统计分析类的,动不动就三四百行,也是首次写那么长的SQL,有用到一些奇形怪状的SQL函数,在这里结合网上的例子做一些笔记,以后用到不记得用法可以翻出来看!

1.基础用法:LISTAGG(XXX,XXX) WITHIN GROUP( ORDER BY XXX),就像聚合函数一样,通过Group by语句,把每个Group的一个字段,拼接起来

LISTAGG()其实可以把它当作SUM()函数来使用或者理解

(1)示例代码:  

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)  AS CITIES
FROM TEMP  
GROUP BY NATION

运行结果:

(2)示例代码:

查询部门为20的员工列表:SELECT t.DEPTNO,t.ENAME FROM SCOTT.EMP t where t.DEPTNO = '20';

运行结果: 

使用  listagg() WITHIN GROUP ()  将多行合并成一行:

SELECT
T .DEPTNO,
LISTAGG (T .ENAME, ',') WITHIN GROUP (ORDER BY T .ENAME) NAMES
FROM SCOTT.EMP T
WHERE
T .DEPTNO = '20' GROUP BY T .DEPTNO

运行结果:

2.高级用法:over(partition by XXX)。在不使用Group by语句时候,也可以使用LISTAGG函数:

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

运行结果:

你可能感兴趣的:(SQL)