类别   名称   日期    
c1 n1    2007-01-01
c2      n1    2007-03-16
c3      n2    2007-04-05
c4      n6    2007-05-12
c2      n3    2007-06-24
c6      n4    2007-07-01
c2      n3    2007-08-01
c3      n5    2007-08-03要求统计数据如下:(日期条件为 2007-03-01  到2007-08-06)
类别     频率    百分比  累计百分比
c1        0         0        0.13
c2        3         0.43     0.38 
c3        2         0.29     0.25 
c4        1         0.14     0.13 
c6        1         0.14     0.13
合计      7          100 
其中累计百分比按全部日期计算

解决方案 »

  1.   

    declare @a table(类别 varchar(10), 名称 varchar(10), 日期  smalldatetime)
    insert @a select 'c1', 'n1', '2007-01-01'
    union all select 'c2', 'n1', '2007-03-16'
    union all select 'c3', 'n2', '2007-04-05'
    union all select 'c4', 'n6', '2007-05-12'
    union all select 'c2', 'n3', '2007-06-24'
    union all select 'c6', 'n4', '2007-07-01'
    union all select 'c2', 'n3', '2007-08-01'
    union all select 'c3', 'n5', '2007-08-03'
    select coalesce(aa.类别,bb.类别) 类别,isnull(频率,0) 频率,str(isnull(百分比,0), 10,2) 百分比,str(isnull(累计百分比,1) ,10,2) 累计百分比 from 
    (select 类别,累计百分比=(count(1)*1.0/(select count(1) from @a)) from @a group by 类别)aa
    full Join
    (select case when grouping(类别)=1 then '合计' else 类别 end 类别,频率=count(1),百分比=count(1)*1.0/(select count(1) from @a where 日期 between '2007-03-01' and '2007-08-06') from @a a 
    where 日期 between '2007-03-01' and '2007-08-06' group by 类别 with rollup)bb
    on aa.类别=bb.类别
      

  2.   

    --result
    /*
    类别         频率          百分比        累计百分比      
    ---------- ----------- ---------- ---------- 
    c1         0                 0.00       0.13
    c2         3                 0.43       0.38
    c3         2                 0.29       0.25
    c4         1                 0.14       0.13
    c6         1                 0.14       0.13
    合计         7                 1.00       1.00(所影响的行数为 6 行)
    */