sql server求和问题

img


求解,sql server如何实现用上一行的余额+借方金额-贷方余额自动填充余额?能否使用触发器实现?上代码

可以的,和正常的写法差不多,只是记得取上一条记录的时候用额外表的一行加个写锁,或者把这个表的第一行加写锁

-- Description:    <Description,,>
-- =============================================
ALTER TRIGGER [dbo].[yuetb_trigger] 
   ON  [dbo].[yuetb]
   AFTER INSERT
AS 
BEGIN

    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for trigger here

    DECLARE TEMP_IGNOR CURSOR FOR select top 1 * from dbo.yuetb order by 序列 for update;
    declare @序列 int;
    SELECT @序列=序列 FROM inserted;
    update dbo.yuetb set 余额=(select top 1 余额 from dbo.yuetb where 序列< @序列 order by 序列 DESC )+isnull(借方,0)-isnull(贷方,0) where 序列=@序列;
END
DEALLOCATE TEMP_IGNOR; 

根据最新序号,获取上一条序号的余额然后跟本次的借贷相加减得出结果

create or replace trigger TRI_testnotnull
  after insert  on  ceshi
  for each row
declare
v_yue int;

 begin
  select a.余额 into v_yue from ceshi a  where a.序号=:new.序号-1;
    update ceshi set b.余额=v_yue+b.借方金额-b.贷方余额 where b.序号>:new.序号   ;

end TRI_testnotnull;

建议通过代码后台逻辑实现最合适了。
触发器方式


-- 插入的时候进行触发器更新
create trigger demo
on tb1
for insert
as
update tb1 set 余额=(select top 1 余额 from tb1 a where a.日期<日期 order by 日期 desc)+isnull(借方,0.00)-isnull(贷方,0.00)
where 序号=你的参数
SELECT [序号]
      ,[日期]
      ,[凭证号]
      ,[摘要]
      ,[借方]
      ,[贷方]
      ,(select top 1 [余额] from [表] order by [序号])-
      (select sum(case when [贷方] is null or [贷方]='' then 0 else [贷方] end)-
      sum(case when [借方] is null or [借方]='' then 0 else [借方] end) from [表] where [序号] <= t.[序号]) as 余额
  FROM [表] t

结果如下:

img

这是一个收支明细公式,直接使用累加函数计算就可以了。sum([余额]+[借方]-[贷方]) over(order by [序号])
结果放入一个临时表中。然后用临时表的值update回原表就可以了。

with tmp as 
(
  SELECT [序号],[日期],[凭证号],[摘要],[借方],[贷方],[余额],sum([余额]+[借方]-[贷方]) over(order by [序号]) as [余额_new]
  from test_eagle
)
update test_eagle
set test_eagle.[余额] = tmp.[余额_new]
from test_eagle,tmp
where test_eagle.[序号] = tmp.[序号]
;

img


SELECT [序号],[日期],[凭证号],[摘要],[借方] ,[贷方]
      ,(select top 1 [余额] from [表] order by [序号])-
      (select sum(case when [贷方] is null or [贷方]='' then 0 else [贷方] end)-
      sum(case when [借方] is null or [借方]='' then 0 else [借方] end) from [表] where [序号] <= t.[序号]) as 余额
  FROM [表] t