数据库里面的数据如下:
id     time        money
1     2007-07-01    5000
2     2007-07-02    4000
.
.
.
2000    2008-12-14   10000
简单的说就是记录每天的销售收入
现在我想用DundasWebChart控件图表展示每个月的平均销售收入,X轴肯定是月份,Y轴就是平均收入。现在涉及到SQL语句的问题,通过选择哪一年下拉框,来选择数据库中的哪一年每个月的平均销售收入,由于数据库中不是每个月都有数据,因此,又不能固定X轴的数字为1-12月,比较棘手的问题。既要选取哪一年的月份,又要选取那一年月份的平均值,这个SQL语句怎么写。不知道是不是我想的太麻烦了,还是怎么回事,大家帮我看看这怎么样实现。

解决方案 »

  1.   

    if not object_id('tempdb..#tmp') is null  drop table #tmp
    select year(time)  as 年份,month(time) as 月份,sum(money) as 数量 
    into #tmp from tablename where year(time)=2008 group by year(time),month(time)
    select ccode,max(case 月份 when 1 then 数量/31 end) 一月,max(case 月份 when 2 then 数量/28 end) 二月,
         max(case 月份 when 3 then 数量/31 end) 三月,max(case 月份 when 4/30 then 数量 end) 四月,
    max(case 月份 when 5 then 数量/31 end) 五月,max(case 月份 when 6 then 数量/30 end) 六月,
    max(case 月份 when 7 then 数量/31 end) 七月,max(case 月份 when 8 then 数量/31 end) 八月,
    max(case 月份 when 9 then 数量/30 end) 九月,max(case 月份 when 10 then 数量/31 end) 十月,
    max(case 月份 when 11 then 数量/30 end) 十一月,max(case 月份 when 12 then 数量/31 end) 十二月
           
          from #tmp where 年份=2008
    group by ccode
    可能还有更好的办法,暂时没想出来,看看后面有没有补充的。这里你要自己去写个函数判断闰年和平年的问题,然后相对执行的脚本也要稍微换下,你再想办法把这个优化下吧
    if not object_id('tempdb..#tmp') is null  drop table #tmp