比如有一张表
编号 类型 数量
 1    A    2
 2    B    6
 3    C    1
 4    B    3
 5    A    5
我要统计同类记录的数量和在总数中占的比例
例子中的总数是2+6+1+3+5=17 类型A的数量和是2+5=8 B是6+3=9 C是1
因此A在总数中占的比例就是8/17=47% B为9/17=52% C为1/17=5%
结果表大致为
类型  比例
 A     47%
 B     52%
 C     5%
请问用一条SQL语句应该怎么写 要求比例用百分比或者小数显示

解决方案 »

  1.   

    select
      类型,
      ltrim(cast(count(1)*100.0/(sleect count(1) from tb) as dec(18,2)))+'%'
    from
      tb
    group by
      类型
      

  2.   

    --修改
    select
      类型,
      ltrim(cast(sum(数量)*100.0/(sleect sum(数量) from tb) as dec(18,2)))+'%'
    from
      tb
    group by
      类型
      

  3.   


    if object_id('tb') >0
    drop table tb
    create table tb
    (
    a int identity,
    b varchar(2),
    c int
    )
    goinsert into tb(b,c)
    select 'a',2
    union all
    select 'b',6
    union all
    select 'c',1
    union all
    select 'b',3
    union all
    select 'a',5
    select b, left(round( sum(c) * 1.00/(select sum(c) from tb) ,2),4)
    from tb
    group by ba 0.41
    b 0.53
    c 0.06