问题描述:
 
通过sql语句可以实现从表a中实现如下的查询
    日期            人数   标本数  金额       
    2009-05-04    10     55    3455.00  但财务部门需要这样的报表做分析    日期            人数   标本数  金额       30内平均金额    90内平均金额
   2009-05-04    10     55    3455.00    3100.00       3500.00后面多了个  30内平均金额 ,90内平均金额,能通过SQL语句实现吗?谢谢了

解决方案 »

  1.   

    select 日期,人数=count(person),标本数=count([sample]),金额=cast(avg(金额) as dec(18,2))
    ,[30内平均金额]=cast(sum(case when 金额<=30 then 金额 else 0 end)*1.0/nullif(sum(case when 金额<=30 then 1 else 0 end),0) as dec(18,2))
    ,[90内平均金额]=cast(sum(case when 金额<=90 then 金额 else 0 end)*1.0/nullif(sum(case when 金额<=90 then 1 else 0 end),0) as dec(18,2))
    from tb
    group by 日期
      

  2.   

    select convert(char(10),日期,120) 日期,人数=count(person),标本数=count([sample]),金额=sum(金额)
            ,[30内平均金额]=(select avg(金额) from tb where 金额 < 30 and datediff(d,日期,a.日期) = 0)
            ,[90内平均金额]=(select avg(金额) from tb where 金额 < 90 and datediff(d,日期,a.日期) = 0)from tb
    group by convert(char(10),日期,120)
      

  3.   


    select 日期,人数=count(person),标本数=count([sample]),金额=cast(avg(金额) as dec(18,2))
            ,[30内平均金额]=cast(sum(case when 金额<=30 then 金额 else 0 end)*1.0/nullif(sum(case when 金额<=30 then 1 else 0 end),0) as dec(18,2))
            ,[90内平均金额]=cast(sum(case when 金额<=90 then 金额 else 0 end)*1.0/nullif(sum(case when 金额<=90 then 1 else 0 end),0) as dec(18,2))
    from tb
    group by 日期
      

  4.   

    It doesn't matter since the method is usable all the same.