日期:2014-05-16  浏览次数:20529 次

如何增加一列,使每一行此列的数据等于前面所有行某一列之和
例如,我现在有这样一个表
   id         date       count     type      
    1       2014-1-1       5         1          
    2       2014-1-2       4         2          
    3       2014-1-2       3         1          
    4       2014-1-3       7         2          
    5       2014-1-3       6         1          

然后想要查询出来的表样是这样
   id         date       count     type       新增列
    1       2014-1-1       5         1          5
    2       2014-1-2       4         2          4
    3       2014-1-2       3         1          8
    4       2014-1-3       7         2          11
    5       2014-1-3       6         1          16
就是新增列等于 对应日期之前 type相同的数量之和.

------解决方案--------------------
create table tb(id int,date datetime,[count] int,[type] int)
insert into tb select 1,'2014-1-1',5,1
insert into tb select 2,'2014-1-2',4,2 
insert into tb select 3,'2014-1-2',3,1
insert into tb select 4,'2014-1-3',7,2
insert into tb select 5,'2014-1-3',6,1  
go
select *,(select sum([count]) from tb where id<=a.id and [type]=a.[type])as s from tb a
/*
id          date                    count       type        s
----------- ----------------------- -----------&