27,579
社区成员
发帖
与我相关
我的任务
分享
select t1.usort,t1.username,(select sum(inmoney) from t2 where t2.uid = t1.uid group by uid ),(select sum(outmoney) from t3 where t3.uid = t1.uid group by uid),money from t1
select T.uid,T.username,T.money,A.inmonet,B.outmoney from user T
left join
(
select uid,sum(inmoney) as inmonet from inmoney where indate between '2010-01-01' and '2010-06-20'
goup by uid
) A on T.uid=A.uid
left join
(
select uid,sum(outmoney) as outmoney from outmoney where outdate between '2010-01-01' and '2010-06-20'
goup by uid
) B on T.uid=B.uid
select T.uid,T.username,A.inmonet,B.outmoney from user T
left join
(
select uid,sum(inmoney) as inmonet from inmoney where indate between '2010-01-01' and '2010-06-20'
goup by uid
) A on T.uid=A.uid
left join
(
select uid,sum(outmoney) as outmoney from outmoney where outdate between '2010-01-01' and '2010-06-20'
goup by uid
) B on T.uid=B.uid
if not object_id('T1') is null
drop table T1
Go
Create table T1([uid] int,[usort] nvarchar(2),[username] nvarchar(2),[money] int)
Insert T1
select 111,N'01',N'张三',200 union all
select 112,N'01',N'李四',550 union all
select 113,N'02',N'王五',168 union all
select 114,N'01',N'陈七',860
Go
if not object_id('T2') is null
drop table T2
Go
Create table T2([id] int,[uid] int,[inmoney] int,[indate] Datetime)
Insert T2
select 1,111,100,'2010-01-10' union all
select 2,112,200,'2010-01-12' union all
select 3,113,100,'2010-01-15' union all
select 4,111,200,'2010-02-18' union all
select 6,114,500,'2010-03-12' union all
select 7,113,400,'2010-03-25' union all
select 8,112,800,'2010-04-10' union all
select 9,114,600,'2010-05-20'
if not object_id('T3') is null
drop table T3
Go
Create table T3([id] int,[uid] int,[outmoney] int,[outdate] Datetime)
Insert T3
select 1,111,100,'2010-01-26' union all
select 2,113,60,'2010-02-11' union all
select 3,112,250,'2010-02-22' union all
select 4,112,200,'2010-03-12' union all
select 5,114,100,'2010-03-20' union all
select 6,113,172,'2010-04-16' union all
select 7,114,140,'2010-05-28'
Go
select a.[usort],
a.[uid],
a.[username],
b.[inmoney],
c.[outmoney],
b.[inmoney]-c.[outmoney][money]
from T1 a
left join
(select [uid],
sum([inmoney])[inmoney]
from T2
group by [Uid]
)b on a.[uid]=b.[uid]
left join
(
select [uid],
sum([outmoney])[outmoney]
from T3
group by [Uid])c
on C.[uid]=b.[uid]
/*
usort uid username inmoney outmoney money
----- ----------- -------- ----------- ----------- -----------
01 111 张三 300 100 200
01 112 李四 1000 450 550
02 113 王五 500 232 268
01 114 陈七 1100 240 860
(4 個資料列受到影響)
*/
select T1.usort,T1.uid,T1.username,a.inmoney,b.outmoney,T1.money from T1
left join (
select uid,SUM(inmoney) as inmoney from T2
where indate between '2010-01-01' and '2010-06-20'
group by uid) a on T1.uid=a.uid
left join (
select uid,SUM(outmoney) as outmoney from T3
where outdate between '2010-01-01' and '2010-06-20'
group by uid) b on T1.uid=b.uid