sql 计算月平均值

收支表
------------
日期 收入 支出
2009-5-22 300 200
2009-6-12 500 100
2009-6-28 300 50

用sql语句 求出每月 平均收入 和 平均支出
也就是先把每月的日收入和支出分别求和 再除以目前共有几个月。请高手帮忙。如果值avg的话,算的似乎就不是月平均值了。
日期 收入 支出
2009-5-22 0 200
2009-6-12 500 0
2009-6-28 0 300
2009-5-10 1000 0
2009-4-10 300 0
大家建个测试表试一下 最后能得出 平均月收入 600 平均支出250 就对了 最后把一条sql语句给我 我测试一下通过了就加分。

beijidefeng 的答案 平均收入 没错 但平均支出 得出的数不对
ytbelwxg 的答案 两数都对 但我想知道有没有简单点的办法,这样执行效率似乎不高。

select year(日期)*100+month(日期),avg(收入),avg(支出)
from 收支表
group by year(日期)*100+month(日期)

这样就可以了


补充 你的意思是输出

日期 收入 支出
2009 367 117 ??

如果是这样的话 那么也好办

select year(日期),avg(收入),avg(支出)
from 收支表
group by year(日期)
这样就是通过年份去分组 然后求平均值

那个说我的这个不行的 你试过没??
我的这个方法在DB2 access 里都用过

不就是access数据库吗?

select year(日期),avg(收入),avg(支出)
from 收支表
group by year(日期)

刚测试过 没有问题 前提是 这里的日期字段是 日期/时间 类型
温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2020-12-21
select sum(收入)/(select count(*) from (select distinct month(日期) from 收支表 where 收入>0 and year(日期)=year(now()))),
sum(支出)/(select count(*) from (select distinct month(日期) from 收支表 where 支出>0 and year(日期)=year(now()))) from 收支表 where year(日期)=year(now())

我在acces里边测试过了,肯定能用,不能用我给你分

以上,希望对你有所帮助!本回答被提问者采纳
第2个回答  2009-08-26
通过substr()函数把日期字段中的年月提取出来,然后分组,求平均值

select substr(日期,1,6) as 年月,
avg(收入) as 平均收入,
avg(支出) as 平均支出
from 收支表
group by substr(日期,1,6);

得到的结果集类似于:

年月 平均收入 平均支出
2009-5 300 200
2009-6 400 75
第3个回答  2009-08-26
select cast(year(日期) as char(4))+'-'+cast(month(日期) as varchar(2)) 月份,sum(收入)/count(*),sum(支出)/count(*)
from 收支表
group by cast(year(日期) as char(4))+'-'+cast(month(日期) as varchar(2))
第4个回答  2009-08-26
select '2009' 年份,
convert(decimal(10,0),SUM(收入)/SUM(case when 收入>0 then 1 else 0 end)) 平均收入,
convert(decimal(10,0),SUM(支出)/SUM(case when 支出>0 then 1 else 0 end)) 平均支出
from 收支表
where year(日期)=2009