在SQL SERVER中表一:
编号 姓名 数量 等第
4001 叶芳      2 A 
4001 叶芳      3 B 
4001 叶芳      1 C 
4001 叶芳      2 D 
4002 张三      2 A 
4002 张三      1 B 
4002 张三      4 C 
4002 张三      2 D 
4002 张三      1 E
我想通在查询得到以下表:(其实就是统计每个人的ABCDE数量各几个,占多少百分比,)
编号 姓名 A数量 A等百分比 B数量 B等百分比 C数量 C等百分比 D数量 D等百分比 E数量 E等百分比
4001 叶芳 2 25  3 37.5   1  12.5   2  25  0  0
4002 张三 2 20  1 10   4  40   2  20  1  10
这样的查询能实现吗?

解决方案 »

  1.   

    declare @s varchar(8000)
    set @s = 'select 编号,姓名 '
    select @s = @s +',['+等第+']=sum(case when 等第='''+等第+''' then 数量 else 0 end),['+等第+'百分比]= sum(case when 等第='''+等第+''' then 数量 else 0 end)/sum(数量) '
    from (select distinct 等第 from tablea ) a
    exec(@s + ' from tablea group by 编号,姓名')
      

  2.   

    create table tablea(编号 int,姓名 varchar(6),数量 int,等第 char(1))
    insert tablea select 4001 ,'叶芳',2,'A'   
    insert tablea select 4001 ,'叶芳',3,'B'   
    insert tablea select 4001 ,'叶芳',1,'C'   
    insert tablea select 4001 ,'叶芳',2,'D'   
    insert tablea select 4002 ,'张三',2,'A'   
    insert tablea select 4002 ,'张三',1,'B'   
    insert tablea select 4002 ,'张三',4,'C'   
    insert tablea select 4002 ,'张三',2,'D'   
    insert tablea select 4002 ,'张三',1,'E'
    godeclare @s varchar(8000)
    set @s = 'select 编号,姓名 '
    select @s = @s +',['+等第+']=sum(case when 等第='''+等第+''' then 数量 else 0 end),['+等第+'等百分比]= sum(case when 等第='''+等第+''' then 数量 else 0 end)*100.0/sum(数量) '
    from (select distinct 等第 from tablea ) a
    exec(@s + ' from tablea group by 编号,姓名')
    drop table tablea 
    /*
    编号          姓名     A           A等百分比                        B           B等百分比                        C           C等百分比                        D           D等百分比                        E           E等百分比                        
    ----------- ------ ----------- ---------------------------- ----------- ---------------------------- ----------- ---------------------------- ----------- ---------------------------- ----------- ---------------------------- 
    4001        叶芳     2           25.000000000000              3           37.500000000000              1           12.500000000000              2           25.000000000000              0           .000000000000
    4002        张三     2           20.000000000000              1           10.000000000000              4           40.000000000000              2           20.000000000000              1           10.000000000000
    */