求一SQL 得出账号余额查询A表示进账表clientIDIndateInresumea2008-10-102000a2018-10-102010b2028-10-102
求一SQL 得出账号余额查询
A表示进账表
clientID Indate Inresume
a 2008-10-10 2000
a 2018-10-10 2010
b 2028-10-10 2020
b 2038-10-10 2030
c 2048-10-10 2040
B表示取账表
clientID Indate Outresume
a 2008-12-10 1000
a 2018-12-10 1010
b 2028-12-10 1020
b 2038-12-10 1030
c 2048-12-10 1040
如何得出每个用户的账号余额,
即
clientID Leftresume
a XXX
b xxx
c xxx
拜谢各位...
[解决办法]
- SQL code
if object_id('[A]') is not null drop table [A]gocreate table [A]([clientID] varchar(1),[Indate] datetime,[Inresume] int)insert [A]select 'a','2008-10-10',2000 union allselect 'a','2018-10-10',2010 union allselect 'b','2028-10-10',2020 union allselect 'b','2038-10-10',2030 union allselect 'c','2048-10-10',2040goif object_id('[B]') is not null drop table [B]gocreate table [B]([clientID] varchar(1),[Indate] datetime,[Outresume] int)insert [B]select 'a','2008-12-10',1000 union allselect 'a','2018-12-10',1010 union allselect 'b','2028-12-10',1020 union allselect 'b','2038-12-10',1030 union allselect 'c','2048-12-10',1040goselect clientid,sum(Inresume) as Leftresumefrom( select clientid,Inresume from a union all select clientid,-Outresume from b) tgroup by clientid/**clientid Leftresume-------- -----------a 2000b 2000c 1000(3 行受影响)**/
[解决办法]
- SQL code
--> 测试数据:[A1]if object_id('[A1]') is not null drop table [A1]create table [A1]([clientID] varchar(1),[Indate] datetime,[Inresume] int)insert [A1]select 'a','2008-10-10',2000 union allselect 'a','2018-10-10',2010 union allselect 'b','2028-10-10',2020 union allselect 'b','2038-10-10',2030 union allselect 'c','2048-10-10',2040--> 测试数据:[B2]if object_id('[B2]') is not null drop table [B2]create table [B2]([clientID] varchar(1),[Indate] datetime,[Outresume] int)insert [B2]select 'a','2008-12-10',1000 union allselect 'a','2018-12-10',1010 union allselect 'b','2028-12-10',1020 union allselect 'b','2038-12-10',1030 union allselect 'c','2048-12-10',1040;with tas(select [clientID],[Inresume] from [A1]union allselect [clientID],-[Outresume] from [B2])select [clientID],SUM([Inresume]) as leftmoney from t group by[clientID]/*clientID leftmoneya 2000b 2000c 1000*/ 