读书人

这样的SQL语句怎么写!

发布时间: 2013-08-04 18:26:15 作者: rapoo

这样的SQL语句如何写!!
有表A (Createtime,MID,Inteset)

时间, 帐号 值 一个MID,不同时间,可能多条记录

2013-07-24 01:10:20,10001,101

2013-07-24 02:10:20,10001,90

2013-07-24 03:10:20,10001,100

2013-07-24 03:10:20,10002,102

......

表B(MID,RemainMargin)

帐号,余额 一个MID,一个RemainMargin指

10001,10000

10002,20000



首先按帐号,然后按时间排序:关联量表,能够直接得到以下记录(流水详细记录)

时间 帐号 利息 结算后余额

2013-07-24 01:10:20,10001,101, 10101 =(RemainMargin+Inteset)

2013-07-24 02:10:20,10001, 90, 10191 =(上一个RemainMargin+Inteset)=10101+90

2013-07-24 03:10:20,10001,100,10291 =10191 +100

2013-07-24 03:10:20,10002,102,20102 =20000+102

......



请大侠们帮看下,如何写一个语句到上表,不然我得用游标,一个个取速度很慢。

非常感谢
这样的SQL语句如何写!! SQL
[解决办法]
上面有误,修正:

create table ta (时间 datetime,帐号 varchar(10),值 int)
insert into ta
select '2013-07-24 01:10:20',10001,101
union all select '2013-07-24 02:10:20',10001,90
union all select '2013-07-24 03:10:20',10001,100
union all select '2013-07-24 03:10:20',10002,102

create table tb(帐号 varchar(10),余额 int)
insert into tb
select 10001,10000
union all select 10002,20000


select * from ta


select * from tb

select a.*,b.余额+(select sum(值) from ta t where t.时间<=a.时间 and t.帐号=a.帐号) as 结算后余额
from ta a
left join tb b on a.帐号=b.帐号

drop table ta,tb

/*
2013-07-24 01:10:20.0001000110110101
2013-07-24 02:10:20.000100019010191
2013-07-24 03:10:20.0001000110010291
2013-07-24 03:10:20.0001000210220102

*/

读书人网 >SQL Server

热点推荐