大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。
Jetbrains全家桶1年46,售后保障稳定
前言:最近在写一些比较复杂的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
运行结果:
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/206844.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...