求一SQL语句,急用,谢谢先~
表中包括"金额"和"年月"列,现在业务要求是求出平均值(上一个月和大上个月的金额和/2).如果大上个月没有值,那么只显示上个月的金额.不知道如何解决,谢谢大家~ 问题点数:50、回复次数:4Top
1 楼yxxx(_小孬)回复于 2005-02-02 13:58:38 得分 0
给一些数据,再给出期望结果Top
2 楼godblessyU(痛并快乐着!)回复于 2005-02-02 14:05:09 得分 0
ID 金额 年月
001 200412
002 400 200411
003 400 200410
结果应该为 年月为200412的值应该为800/2 .
如果200410为空那么只显示200411的400金额Top
3 楼ORARichard(没钱的日子......)回复于 2005-02-02 14:12:33 得分 30
--try:
select a.年月,(a.金额+b.金额)/2 平均值 from
(
select rownum no,金额,年月 from
(
select * from tb where 年月>=开始年月 and 年月<=结止年月 order by 年月
)
) a,
(
select 1 no,金额,年月 from tb where 年月=开始年月 union all
select rownum+1,金额,年月 from
(
select 金额,年月 from tb where 年月>=开始年月 and 年月<=结止年月 order by 年月
)
) b
where a.no=b.no;Top
4 楼jiangchuanli(大山)回复于 2005-02-02 15:45:12 得分 20
这个SQL我测试了,可行。
假定本月为'200412':
select sum(金额)/2 as 平均值 from test
where 年月 < '200412' --不包含本月
and 年月 >= to_char(add_months(to_date('200412','yyyymm'),-2),'yyyymm') --有上一个月和大上个月的
Top




