当前位置: 代码迷 >> Sql Server >> 怎么在新建记录的同时计算累计值
  详细解决方案

怎么在新建记录的同时计算累计值

热度:65   发布时间:2016-04-27 12:31:21.0
如何在新建记录的同时计算累计值?
假设表结构如下:
id orgID date Amount totalAmount
1 1001 2012-2-1 20 20
2 1002 2012-2-1 10 10
3 1003 2012-2-1 5 5
4 1001 2012-2-2 10 30
5 1002 2012-2-3 10 20
6 1003 2012-2-4 5 10
......
即在插入一条新记录时,自动计算出同一ORGID的累计值。用触发器可以不?如何实现?


------解决方案--------------------
SQL code
exec cs#'$tblid orgID date Amount1 1001 2012-2-1 202 1002 2012-2-1 103 1003 2012-2-1 54 1001 2012-2-2 105 1002 2012-2-3 106 1003 2012-2-4 5'--> 测试数据:[tbl]if object_id('[tbl]') is not null drop table [tbl]gocreate table [tbl]([id] int,[orgID] int,[date] datetime,[Amount] int)goinsert [tbl]select 1,1001,'2012-2-1',20 union allselect 2,1002,'2012-2-1',10 union allselect 3,1003,'2012-2-1',5 union allselect 4,1001,'2012-2-2',10 union allselect 5,1002,'2012-2-3',10 union allselect 6,1003,'2012-2-4',5;with tas(select ROW_NUMBER()Over(PARTITION by [orgID] order by getdate())as num,*,Amount as total from tbl),mas(select num,id,orgID,[date],Amount,total from t where num=1union allselect a.num,a.id,a.orgID,a.[date],a.Amount,b.total+a.Amount from t ainner join m bon a.num=b.num+1 and a.orgID=b.orgID)select id, orgID, [date], Amount, total from m order by orgID/*id    orgID    date    Amount    total1    1001    2012-02-01 00:00:00.000    20    204    1001    2012-02-02 00:00:00.000    10    302    1002    2012-02-01 00:00:00.000    10    205    1002    2012-02-03 00:00:00.000    10    103    1003    2012-02-01 00:00:00.000    5    56    1003    2012-02-04 00:00:00.000    5    10*/这个就是统计数据,你可以给它写到触发器里面
------解决方案--------------------
探讨

这么复杂啊?!谢谢指导。

不过我不求现有数据的累计值,而是在每插入一条新记录的时候计算出累计值并保存到表中。也就是同一ORGID前一条记录的的totalAmount + 新记录的Amount

------解决方案--------------------
探讨
假设表结构如下:
id orgID date Amount totalAmount
1 1001 2012-2-1 20 20
2 1002 2012-2-1 10 10
3 1003 2012-2-1 5 5
4 1001 2012-2-2 10 30
5 1002 2012-2-3 10 20
6 1003 2012-2-4 5 10
......
即在插入一条新记录时,自动……

------解决方案--------------------
一般来讲,计算量最好不要保存在表里,假如中间有一条记录的值发生变化,那后面的值是不是都会跟着要发生变化

你的问题可以用触发器解决,可以用前触发,也可以用后触发

但我还是倾向于查询的时候再统计
------解决方案--------------------
;with t
as(
select ROW_NUMBER()Over(PARTITION by [orgID] order by getdate())as num,
*,Amount as total from tbl
),


为什么是order by getdate(),为什么不是 order by date
------解决方案--------------------
首先在這個表裡面加一個批次號 BatchNo之類的唯一值.
insert的後面調用個sp
SQL code
create PROCEDURE xxx_SP@BatchNo    NVARCHAR(50)ASdeclare @orgID nvarchar(10)declare @Cur cursor begin SET @Cur = CURSOR FOR (SELECT orgID FROM dt where [email protected])        OPEN @Cur        FETCH NEXT FROM @Cur INTO @orgID         WHILE(@@FETCH_STATUS = 0)        BEGIN                  update dt set totalAmount = select sum (Amount ) from dt where [email protected] group by Amount where [email protected] and [email protected] end
  相关解决方案