新网实名认证:sql数据库查询问题

来源:百度文库 编辑:中科新闻网 时间:2024/05/03 01:50:55
有一个表 有两个字段 user(用户) 和 money 花费金额
表内容为 user money
100 60
100 50
100 40
200 40
200 50
200 60
300 50
300 60
400 70
400 60
大致如下, 我想利用这个表查询出每个用户花费金额之和结果如下
100 150
200 150
300 110
400 130
具体的sql语句应该怎么写?

select sum(money) as tmoney from [你的表名称] group by user

create table t1(userid int,u_money int)
insert t1 select 100,60
union all select 100,50
union all select 100,50
union all select 200,40
union all select 200,40
union all select 300,70

go

create function f(@u int)
returns varchar(8000)
as
begin
declare @re varchar(8000)
set @re=''
select @re=@re+u_money from t1 where userid=@u
return @re
end
go

select userid,u_sum=dbo.f(userid)
from t1
group by userid
go

drop table t1
drop function f

select user,sum(money) as money from table group by user order by user

select sum(money) as tmoney from table group by user