日期:2014-05-18  浏览次数:20533 次

求教一个有点难度的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