sum over 分析函数用法

 

sum over 分析函数用法

首先表如下:

 

A

B

C

D

1

A                               

1                               

2                               

3                               

2

B                               

1                               

3                               

4                               

3

C                               

2                               

4                               

5                               

4

D                               

2                               

5                               

6                               

5

E                               

3                               

6                               

7                               

over的用法:

over主要是和汇总函数配合产生出额外的列                 

例如:SELECT T.A ,T.B,T.C,SUM(C) OVER(PARTITION BY B ORDER BY A) SUM1 FROM TEST T

这句的意思是:从TEST表中查出A,B,C三列再加上SUM1这一列,SUM1是以A列排序,以B列分组,从C列

连续加总得到的数放在对应的SUM1列里面,例如:SUM1=5表示B=1的并且在第二行以前的和即2+3=5

 

A

B

C

SUM1

1

A                               

1                               

2                               

2

2

B                               

1                               

3                               

5

3

C                               

2                               

4                               

4

4

D                               

2                               

5                               

9

5

E                               

3                               

6                               

6

SUM(C)是汇总函数,也可以用其它的如:AVG(),COUNT()等

PARTITION 是指定按哪行分组

ORDER 指定排序,用在OVER函数里说明是连续的进行汇总。如果不加的话结果如下:

SELECT T.A ,T.B,T.C,SUM(C) OVER(PARTITION BY B ORDER BY T.A) SUM1 ,SUM(C) OVER(PARTITION BY B ) SUM2 FROM TEST T

 

A

B

C

SUM1

SUM2

1

A                               

1                               

2                               

2

5

2

B                               

1                               

3                               

5

5

3

C                               

2                               

4                               

4

9

4

D                               

2                               

5                               

9

9

5

E                               

3                               

6                               

6

6

注意SUM1和SUM2的区别。

注:

1、如果先partition by X后order by Y则在分组的前提下,同组中X字段值一样的记录再按Y字段排序,然后sum(a)over()的作用就是按a字段累加----分组连续求和

2、若没有order by Y则sum(a) over()的执行是把分组后同组的记录一起处理,当作一条记录来看待----分组求总和

3、若两者皆没有,即sum(a)over(),over后的括号中为空,则sum(a)over()字段的值为a列所有值的和,每一条记录的sum(a)over()都一样----求总和

转自:http://ljx198308.blog.163.com/blog/static/176274246201011935246547/?fromdm&fromSearch&isFromSearchEngine=yes

你可能感兴趣的:(Oracle)