Sql代碼
over(Partition by…) 一個超級牛皮的ORACLE特有函數
最近工作中才接觸到這個功能強大而靈活的函數
oracle的分析函數over 及開窗函數
一
Oracle從
下面通過幾個例子來說明其應用
date sale
規則
得到的結果
DATE SALE SUM
NAME CLASS S
fda
ffd
dss
cfe
gds
gf
ddd
adf
asdf
通過
select * from
(
select name
)
where mm=
得到結果
NAME CLASS S MM
dss
gds
gf
ddd
注意
A B C
m a
n a
m a
n b
n b
x b
x b
x b
h b
select a
得到結果
A B C SUM(C)OVER(PARTITIONBYA)
h b
m a
m a
n a
n b
n b
x b
x b
x b
如果用sum
A SUM(C)
h
m
n
x
無法得到B列值
=====
select * from test
數據
A B C
select a
from test
A B C C_SUM
eg: 就是將C的欄位值summary 放在每行後面
select a
from test
A B C C_SUM
求個人工資占部門工資的百分比
SQL> select * from salary;
NAME DEPT SAL
a
b
c
d
SQL> select name
NAME DEPT SAL PERCENT
a
b
c
d
二
開窗函數指定了分析函數工作的數據窗口大小
over(order by salary) 按照salary排序進行累計
over(partition by deptno)按照部門分區
over(order by salary range between
每行對應的數據窗口是之前行幅度值不超過
例如
aa
sum(aa)over(order by aa range between
得出的結果是
AA SUM
對於aa=
又如 對於aa=
over(order by salary rows between
每行對應的數據窗口是之前
over(order by salary rows between unbounded preceding and unbounded following)
每行對應的數據窗口是從第一行到最後一行
over(order by salary range between unbounded preceding and unbounded following)
等效
over(partition by null)
常用的分析函數如下所列
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 …)
示例
SQL> select type
TYPE QTY
SQL> select type
TYPE QTY CNT
SQL> select * from test;
SQL> select t
(select rownum rn from (select max(to_number(id)) mid from test) connect by rownum <=mid ))L
order by id
ID MC TO_CHAR(B
*******************************************************************
關於partition by
這些都是分析函數
select deptno
select deptno
select deptno
select deptno
select deptno
order by deptno;
select deptno
select deptno
round(avg(sal) over(partition by deptno)) as dept_avg_sal
round(sal
from emp;
From:http://tw.wingwit.com/Article/program/Oracle/201311/18056.html