设表数据如下:[A] [B] [C]
 1   a   tt
 1   a   tt
 1   a   tt
 1   b   tt
 2   a   tt
 2   a   tt
 2   b   tt
 2   b   tt要得到结果集如下:
[A] [B_a] [B_b]
 1  3     1
 2  2     2即:
结果集的行数为原数据distinct [A]的行数
分别统计每一个[A]出现a或b的次数从我要的结果集看,以第一行为例,我要得到的数据为:
1,3,1
表示:原数据中,[A]=1 and [b]='a'的行数有3行,这个3这个数值就填充在结果集[B_a]中。
而 [A]=1 and [b]='b'的行数有1行,这个1这个数值就填充在结果集[B_b]中。有没有可能得到这样的结果集?谢谢。

解决方案 »

  1.   


    create table piao
    ([A] int, [B] varchar(4), [C] varchar(4))insert into piao
    select 1, 'a', 'tt' union all
    select 1, 'a', 'tt' union all
    select 1, 'a', 'tt' union all
    select 1, 'b', 'tt' union all
    select 2, 'a', 'tt' union all
    select 2, 'a', 'tt' union all
    select 2, 'b', 'tt' union all
    select 2, 'b', 'tt'
    select t1.A,
    (select count(1) from piao t2 where t2.A=t1.A and t2.B='a') 'B_a',
    (select count(1) from piao t2 where t2.A=t1.A and t2.B='b') 'B_b'
    from piao t1
    group by t1.A/*
    A           B_a         B_b
    ----------- ----------- -----------
    1           3           1
    2           2           2(2 row(s) affected)
    */
      

  2.   

    谢谢楼上的回复,这样的写法我也懂。
    但问题是:列[B]中的值,远远不止只有'a'或'b',还有可能其它更多想不到的值。
      

  3.   


    -- 建测试表
    create table piao
    ([A] int, [B] varchar(4), [C] varchar(4))-- 列[B]含a,b,c,d,e
    insert into piao
    select 1, 'a', 'tt' union all
    select 1, 'a', 'tt' union all
    select 1, 'a', 'tt' union all
    select 1, 'b', 'tt' union all
    select 1, 'd', 'tt' union all
    select 2, 'a', 'tt' union all
    select 2, 'a', 'tt' union all
    select 2, 'b', 'tt' union all
    select 2, 'b', 'tt' union all
    select 2, 'c', 'tt' union all
    select 2, 'd', 'tt' union all
    select 2, 'e', 'tt'
    -- 动态SQL统计个数 
    declare @sql varchar(6000)select @sql='
    select A,'+
    stuff((select distinct ',isnull([B_'+B+'],0) B_'+B from piao for xml path('')),1,1,'')
    +' from (select A,''B_''+B B,count(1) ct from piao group by A,B) t
    pivot(max(ct) for B in('+ 
    stuff((select distinct ',[B_'+B+']' from piao for xml path('')),1,1,'')+')) p 'exec(@sql)-- 结果
    /*
    A           B_a         B_b         B_c         B_d         B_e
    ----------- ----------- ----------- ----------- ----------- -----------
    1           3           1           0           1           0
    2           2           2           1           1           1(2 row(s) affected)
    */