• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
鱼要的是海洋,鸟要的是天空,我要的是自由!
平凡的人不平凡的人生
博客园    首页    新随笔    联系   管理    订阅  订阅

组合处理

原贴地址:
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

posted @ 2007-06-29 16:36  伊凡  阅读(226)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3