读书人

简单联合查询忘光光了,该怎么解决

发布时间: 2012-01-18 00:23:26 作者: rapoo

简单联合查询,忘光光了
情况如下:
表A
用户 余额
1 100
2 100
3 59
4 60
表B
用户 预支时间 预支金额
1 8月2日 30
1 8月3日 50
3 8月2日 30
4 8月2日 30

我 现在需要显示的是
用户 余额 预支金额之和 预支次数
1 100 80 2
3 59 50 1
4 60 30 1

请问如何能高效的解决? 谢谢

[解决办法]
declare @t table(用户 int,余额 int)
insert into @t
select 1,100
union all select 2,100
union all select 3,59
union all select 4,60
declare @b table(用户 int,预支时间 varchar(20),预支金额 int)
insert into @b
select 1, '8月2日 ',30
union all select 1, '8月3日 ',50
union all select 3, '8月2日 ',30
union all select 4, '8月2日 ',30


select a.*,sum(b.预支金额) 预支金额之和 ,count(b.用户) 预支次数 from @t a inner join @b b
on a.用户=b.用户
group by a.用户,a.余额,b.用户
order by a.用户

[解决办法]
select a.用户,a.余额,t.预支金额之和,t.预支次数
from 表A a,(
select 用户,sum(预支金额) as 预支金额之和,count(*) as 预支次数
from 表B
group by 用户
) as t
where a.用户=t.用户
[解决办法]
select T1.用户,sum(T2.预支金额) AS 预支金额之和 ,count(T2.用户) AS 预支次数 from 表A T1 inner join 表B T2
on T1.用户=T2.用户
group by T1.用户,T1.余额,T2.用户
order by T1.用户

读书人网 >SQL Server

热点推荐