分析函数语法:
例: sum(sal) over (partition by deptno order by ename) new_alias
sum就是函数名
(sal)是分析函数的参数,每个函数有0~3个参数,参数可以是表达式,例如:sum(sal+comm)
over 是一个关键字,用于标识分析函数,否则查询分析器不能区别sum()聚集函数和sum()分析函数
分析函数用于计算基于组的某种聚合值,它和聚合函数的不同之处是:对于每个组返回多行,而聚合函数对于每个组只返回一行。
常用的分析函数如下所列:
row_number() over(partition by ... order by ...)
rank() over(partition by ... order by ...)
dense_rank() over(partition by ... order by ...)
count() over(partition by ... order by ...)
max() over(partition by ... order by ...)
min() over(partition by ... order by ...)
sum() over(partition by ... order by ...)
avg() over(partition by ... order by ...)
first_value() over(partition by ... order by ...)
last_value() over(partition by ... order by ...)
lag() over(partition by ... order by ...)
lead() over(partition by ... order by ...)
select * from test
DMPNO NAME DPTNO MAR SAL
0075 xu D1 0082 3000
0082 bao D1 0096 4000
0096 zhao D2 5000
0111 mu D2 0082 4000
0056 zhang D3 0111 3000
0923 wang D3 0075 2000
0001 xiu D1 0082 6000
0002 feng D1 0082 7000
0005 wu D2 0111 3000
select DMPNO,SAL,NAME,DPTNO,
sum(sal) over (order by name) A, --連続求和
sum(sal) over () B, -- 此sum(sal) over () 等同于sum(sal)
sum(sal) over (partition by dptno order by name) C, --按部門"連続"求和
sum(sal) over (partition by dptno) D --按部門求和
FROM TEST
DMPNO SAL NAME DPTNO A B C D
0082 4000 bao D1 4000 37000 4000 20000
0002 7000 feng D1 11000 37000 11000 20000
0111 4000 mu D2 15000 37000 4000 12000
0923 2000 wang D3 17000 37000 2000 5000
0005 3000 wu D2 20000 37000 7000 12000
0001 6000 xiu D1 26000 37000 17000 20000
0075 3000 xu D1 29000 37000 20000 20000
0056 3000 zhang D3 32000 37000 5000 5000
0096 5000 zhao D2 37000 37000 12000 12000
row_number()over() ,rank()over() 和 dense_rank()over()函数的使用:
①select name,dptno,sal,rank()over(partition by dptno order by sal desc) mm from test
--select name,dptno,sal,row_number()over(partition by dptno order by sal desc) mm from test
--select name,dptno,sal,dense_rank()over(partition by dptno order by sal desc) mm from test
NAME DPTNO SAL MM
feng D1 7000 1
xiu D1 6000 2
bao D1 4000 3
xu D1 3000 4
zhao D2 5000 1
mu D2 4000 2
wu D2 3000 3
zhang D3 3000 1
wang D3 2000 2
注意:(select* from ① where mm='1')
1.在求第一名的时侯:不能用row_number(),因为如果有两个并列第一,row_number()只返回一个结果;
2.rank()和dense_rank()区别:
--rank()是跳跃排序,有两个第二名时接下来就是第四名;