1.row_number 函数
区别于其它排序函数,相当于多了一个排序的列
数据准备
name money
ming 12
yang 23
ming 35
ming 54
yang 43
select name,money,row_number() over(order by money) from lei_test;
ming 12 1
yang 23 2
ming 35 3
yang 43 4
ming 54 5
select name,money,row_number()
over(partition by name order by money)
from lei_test;
ming 12 1
ming 35 2
ming 54 3
yang 23 1
yang 43 2
select name,money,tb
from
(select name,money,row_number()
over(partition by name order by money) tb
from lei_test) ta
where tb=1;
ming 12 1
yang 23 1
2.rank()函数与row_number函数类似
区别,相同成绩会并列,序列不连接
select name,money,rank()
over(partition by name order by money)
from lei_test;
ming 12 1
ming 12 1
ming 35 3
ming 54 4
yang 23 1
yang 43 2
DENSE_RANK
3.dense_rank函数与row_number函数类似
区别,相同成绩会并列,序列连接
select name,money,dense_rank()
over(partition by name order by money)
from lei_test;
ming 12 1
ming 12 1
ming 35 2
ming 54 3
yang 23 1
yang 43 2
4.cume_dist() 小于等于当前值的行数/分组内总行数
select name,money,CUME_DIST()
over(partition by name order by money)
from lei_test;
ming 12 0.5
ming 12 0.5
ming 35 0.75
ming 54 1.0
yang 23 0.5
yang 43 1.0
5.percent_rank() 分组内当前行的RANK值-1/分组内总行数-1
select name,money,percent_rank()
over(partition by name order by money)
from lei_test;
ming 12 0.0
ming 12 0.0
ming 35 0.6666666666666666
ming 54 1.0
yang 23 0.0
yang 43 1.0
6.ntile(n)函数,将数据分成n份
select name,money,ntile(2)
over(partition by name order by money)
from lei_test;
ming 12 1
ming 12 1
ming 35 2
ming 54 2
yang 23 1
yang 43 2
############################分析函数完
窗口函数
####################################
7.LEAG(col,n,DEFAULT) 用于统计窗口内往上第n行值
select name,money,lead(money,1)
over(partition by name order by money)
from lei_test;
ming 12 12
ming 12 35
ming 35 54
ming 54 NULL
yang 23 43
yang 43 NULL
8.LAG(col,n,DEFAULT) 用于统计窗口内往下第n行值
select name,money,lag(money,1)
over(partition by name order by money)
from lei_test;
9.FIRST_VALUE()得到排序后第一个
select name,money,FIRST_VALUE(money)
over(partition by name order by money)
from lei_test;
ming 12 12
ming 12 12
ming 35 12
ming 54 12
yang 23 23
yang 43 23
10.取分组内排序后,截止到当前行,最后一个值
select name,money,last_VALUE(money)
over(partition by name order by money)
from lei_test;
ming 12 12
ming 12 12
ming 35 35
ming 54 54
yang 23 23
yang 43 43