这样的SQL语句如何写!!

飞猫0213 2013-07-24 10:24:46
有表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

......



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

非常感谢
...全文
141 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
kobemadi 2013-07-25
  • 打赏
  • 举报
回复
学习了
火拼阿三 2013-07-25
  • 打赏
  • 举报
回复
select a.*,b.余额,(a.值+b.余额) as 总数 from ta a,tb1 b where a.帐号=b.帐号
飞猫0213 2013-07-24
  • 打赏
  • 举报
回复
非常感谢楼上的帮忙!
Andy__Huang 2013-07-24
  • 打赏
  • 举报
回复
上面有误,修正:
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.000	10001	101	10101
2013-07-24 02:10:20.000	10001	90	10191
2013-07-24 03:10:20.000	10001	100	10291
2013-07-24 03:10:20.000	10002	102	20102

*/
Andy__Huang 2013-07-24
  • 打赏
  • 举报
回复
引用
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.*,a.值+b.余额 as 结算后余额 from ta a left join tb b on a.帐号=b.帐号 drop table ta,tb /* 2013-07-24 01:10:20.000 10001 101 10101 2013-07-24 02:10:20.000 10001 90 10090 2013-07-24 03:10:20.000 10001 100 10100 2013-07-24 03:10:20.000 10002 102 20102 */

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧