日期:2014-05-17  浏览次数:20508 次

SQL如何取得到连续期数中的往期的金额的合计
比如
表a

帐号 期数 金额 时间
a 1 10 2012-01-01
a 2 20 2012-02-01
a 3 30 2012-03-01
a 4 40 2012-04-11
b 1 50 2012-06-21

想得到的结果是 金额合计等于(小于等于当前期数的金额的合计)

帐号 期数 金额合计 时间
a 1 10 2012-01-01
a 2 30 2012-02-01
a 3 60 2012-03-01
a 4 100 2012-04-11
b 1 50 2012-06-21


建临时数据如下

declare @表a table (帐号 varchar(1),期数 int,金额 int ,时间 varchar(20))
insert into @表a
select 'a',1,10,'2012-01-01' union all
select 'a',2,20,'2012-02-11' union all
select 'a',3,30,'2012-03-21' union all
select 'a',4,40,'2012-04-01' union all
select 'b',1,50,'2012-05-01' 







------解决方案--------------------
declare @表a table (帐号 varchar(1),期数 int,金额 int ,时间 varchar(20))
insert into @表a
select 'a',1,10,'2012-01-01' union all
select 'a',2,20,'2012-02-11' union all
select 'a',3,30,'2012-03-21' union all
select 'a',4,40,'2012-04-01' union all
select 'b',1,50,'2012-05-01'

select 
帐号,期数,
金额=(select sum(金额) from @表a where 帐号=t.帐号 and 时间<=t.时间),
时间 
from @表a t
/*
帐号 期数 金额 时间
---- ----------- ----------- --------------------
a 1 10 2012-01-01
a 2 30 2012-02-11
a 3 60 2012-03-21
a 4 100 2012-04-01
b 1 50 2012-05-01
*/

SQL code

declare @表a table (帐号 varchar(1),期数 int,金额 int ,时间 varchar(20))
insert into @表a
select 'a',1,10,'2012-01-01' union all
select 'a',2,20,'2012-02-11' union all
select 'a',3,30,'2012-03-21' union all
select 'a',4,40,'2012-04-01' union all
select 'b',1,50,'2012-05-01'  

select 
    帐号,期数,
    金额=(select sum(金额) from @表a where 帐号=t.帐号 and 时间<=t.时间),
    时间 
from @表a t
/*
帐号   期数          金额          时间
---- ----------- ----------- --------------------
a    1           10          2012-01-01
a    2           30          2012-02-11
a    3           60          2012-03-21
a    4           100         2012-04-01
b    1           50          2012-05-01
*/

------解决方案--------------------
SQL code
select 
    帐号,期数,
    金额=(select sum(金额) from @表a where 帐号=t.帐号 and 期数<=t.期数),
    时间 
from @表a t

------解决方案--------------------
SQL code
declare @表a table (帐号 varchar(1),期数 int,金额 int ,时间 varchar(20))
insert into @表a
select 'a',1,10,'2012-01-01' union all
select 'a',2,20,'2012-02-11' union all
select 'a',3,30,'2012-03-21' union all
select 'a',4,40,'2012-04-01' union all
select 'b',1,50,'2012-05-01'  

SELECT 帐号,期数,
金额=(select SUM(金额) FROM @表a WHERE 帐号=t.帐号 AND 期数<=t.期数 )
,时间
FROM @表a AS t
/*
帐号   期数          金额          时间
---- ----------- ----------- --------------------
a    1           10          2012-01-01
a    2           30          2012-02-11
a    3           60          2012-03-21
a    4           100         2012-04-01
b    1           50          2012-05-01

(5 行受影响)

*/