欢迎投稿

今日深度:

sum over用法,以及与group by的区别

sum over用法,以及与group by的区别


1、sum over用法

sum(col1) over(partition by col2 order by col3 )

以上的函数可以理解为:按col2 进行分组(partition ),每组以col3 进行排序(order),并进行连续加总(sum)

表a,内容如下:  
 B   C  D  
02 02 1  
02 03 2  
02 04 3  
02 05 4  
02 01 5  
02 06 6  
02 07 7  
02 03 5  
02 02 12  
02 01 2  
02 01 23  

执行:SELECT   b,   c,   d,   SUM(d)   OVER(PARTITION   BY   b,c   ORDER   BY   d)   e   FROM   a  

得到结果:

B   C   E  
02 01 2  
02 01 7  
02 01 30  
02 02 1  
02 02 13  
02 03 2  
02 03 7  
02 04 3  
02 05 4  
02 06 6  
02 07 7  

可以看到,E列的值是累加和。


2、与group by 的区别

同样的a表:select   b,c,sum(d)   e   from   a   group   by   b,c  

B   C   E  
02 01 30  
02 02 13  
02 03 7  
02 04 3  
02 05 4  
02 06 6  
02 07 7

区别很明显。

www.htsjk.Com true http://www.htsjk.com/shujukunews/1922.html NewsArticle sum over用法,以及与group by的区别 1、sum over用法 sum(col1) over(partition by col2 order by col3 ) 以上的函数可以理解为:按col2 进行分组(partition ),每组以col3 进行排序(order),并进行连续加总(...
评论暂时关闭