组合处理

原贴地址:
http://community.csdn.net/Expert/topic/3338/3338785.xml?temp=.9853022

有表t1:
ID | Place Time  Level
---|-------------------
 1 |  P1    T3    L1   
 2 |  P1    T1    L1   
 3 |  P3    T1    L2   
 4 |  P2    T2    L3   
 5 |  P1    T1    L1   
 6 |  P2    T3    L3   

想实现的是:

生成字段间的所有项的组合,并统计表t1中包含该组合的纪录的条数(只统计有数据的组合)

1项组合
item  count
 P1    3
 P2    2
.....

2项组合
item   count
 P1_T1   2
 P1_T3   1
....

3项组合
item   count
 P1_T1_L1   2
 P1_T1_L2   1
....

-----------------------------------------------------------------------

--示例

--示例数据
create table t1(ID int,Place varchar(10),Time varchar(10),Level varchar(10),aa varchar(10))
insert t1 select 1,'P1','T3','L1','aa'
union all select 2,'P1','T1','L1','bb'
union all select 3,'P3','T1','L2','aa'
union all select 4,'P2','T2','L3','aa'
union all select 5,'P1','T1','L1','aa'
union all select 6,'P2','T3','L3','bb'
go

--通用的处理存储过程
create proc p_qry
@count int=1 --组合的项数
as
declare @sa Nvarchar(4000),@sb Nvarchar(4000)
declare @s2 Nvarchar(4000),@s3 Nvarchar(4000)
declare @s varchar(8000)

if isnull(@count,0)<0 set @count=1
select a=name,b=colid
into #t from syscolumns
where id=object_id(N't1') and name<>'ID'
set @count=case when @count>@@rowcount then @@rowcount else @count end

if @count=1
 set @sa='select @s=@s+'' union all select item=[''+a+''],[count]=count(*) from t1 group by [''+a+'']'' from #t'
else
begin
 select @sa='select @s=@s+'' union all select item=[''+a.a+'']'''
  ,@sb='''[''+a.a+'']'''
  ,@s2='from #t a'
  ,@s3='where a.b'
 while @count>1
  select @count=@count-1
   ,@sa=@sa+'+''+''''_''''+[''+'+char(@count/26+97)+char(@count%26+97)+'.a+'']'''
   ,@sb=@sb+'+'',[''+'+char(@count/26+97)+char(@count%26+97)+'.a+'']'''
   ,@s2=@s2+',#t '+char(@count/26+97)+char(@count%26+97)
   ,@s3=@s3+'<'++char(@count/26+97)+char(@count%26+97)+'.b'
    +' and '++char(@count/26+97)+char(@count%26+97)+'.b'
 select @sa=@sa+'+'',[count]=count(*) from t1 group by ''+'+@sb+' '+@s2+' '+left(@s3,len(@s3)-9)
end

set @s=''
exec sp_executesql @sa,N'@s varchar(8000) out',@s out
set @s=stuff(@s,1,11,'')
exec(@s)
go

--调用
exec p_qry 3
go

--删除测试
drop table t1
drop proc p_qry

你可能感兴趣的:(组合)