【SQL 编程你也行】SQL Server新功能之函数:sum函数(2005、2008、2012、2014)

  • Post author:
  • Post category:其他



sum函数在SQL Server 2005中,添加了 over(partition by )的功能。


在2012、1014中添加了 over(partition by  order by )的功能,以及rows/range功能。


下面是具体的例子:

if object_id('test') is not null
   drop table test
go

create table test
(
id int  primary key,
name varchar(20),
groupname varchar(20)
)

insert into test
values(1,'小明','开发部'),
      (4,'小张','开发部'),
      (5,'小白','开发部'),

      (8,'小王','财务部'),
      (9, null,'财务部'),
      (15,'小刘','财务部'),

	  (16,'小高','行政部'),
      (18,'小王','行政部'),
	  (23,'小李','行政部'),
	  (29,'小吴','行政部');

select *,
       sum(id) over(partition by groupname ) 每个组的id之和,

	   sum(id) over(partition by groupname order by id) 每个组的id之和,

	   sum(id) over(order by id)  id之和
from test 


select *,

       sum(id) over(partition by groupname 
	                    order by id 
						rows between current row and unbounded following) 当前行_最后1行,

       sum(id) over(partition by groupname 
	                    order by id 
						rows between unbounded preceding and current row) 第1行_当前行
from test 


转载于:https://www.cnblogs.com/momogua/p/8304456.html