读书人

求教一个有点难度的sql计算若干条记

发布时间: 2012-01-31 21:28:41 作者: rapoo

求教一个有点难度的sql,计算若干条记录的平均值
某表字段:客户号,月份,金额
某个客户号可能有1~N的多条记录(月份不同)

现在要计算平均值,比如如下记录
001 200701 100.00
001 200702 200.00
002 200701 100.00
002 200702 200.00
002 200703 300.00
-------------------------
得到如下输出
001 150
002 200

请问如何写sql,或者用临时表也可以~

[解决办法]
select 客户号,avg(金额) as 金额 from 表
group by 客户号
[解决办法]
create table test(
kh varchar(3),
yf varchar(6),
je int
)
insert into test
select '001 ', '200701 ',100 union all
select '001 ', '200702 ',200 union all
select '002 ', '200701 ',100 union all
select '002 ', '200702 ',200 union all
select '002 ', '200701 ',300

select kh,avg(je) as je from test
group by kh

drop table test
[解决办法]
create table test(客户号 varchar(10),月份 varchar(15),金额 decimal(10,2))
insert test select '001 ', '200701 ',100.00
union all select '001 ', '200702 ',200.00
union all select '002 ', '200701 ',100.00
union all select '002 ', '200702 ',200.00
union all select '002 ', '200703 ',300.00

select 客户号,金额=ltrim(str(avg(金额),10,0)) from test group by 客户号
[解决办法]
客户号 金额
---------- ----------
001 150
002 200

读书人网 >SQL Server

热点推荐