日期:2014-05-18  浏览次数:20447 次

求一sql语句(sql2008)
设表数据如下:

[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]中。

有没有可能得到这样的结果集?谢谢。


------解决方案--------------------
SQL code

-- 建测试表
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)
*/