组合处理
来源:互联网 发布:sql数据库工程师 编辑:程序博客网 时间:2024/04/29 23:47
原贴地址:
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
- 组合处理
- 组合处理
- 组合处理
- 组合处理
- 组合处理
- 组合处理
- 组合处理
- 组合处理
- 组合处理
- 组合处理
- 组合处理
- 组合处理
- 组合处理
- 组合处理
- 8.3 处理组合行为
- 自定义组合控件处理
- 处理键盘组合键消息
- 组合模式 -- 树形结构处理
- 中国美眉如何幽默地拒绝外国男人
- 感受死亡
- 放弃理想,未必能成就现实
- 我该怎样学好数据结构啊---我就要死了
- Spring研究 (4) Bean的配置
- 组合处理
- 第一个spring实例
- 9月2日写的文章丢了-CSDN,怎么搞的
- Matlab下载地址
- 那只咖啡水杯
- 深入浅出PE文件格式---自己动手打造PE Show
- Symbian开发环境的建立
- PEAR::HTML_QuickForm入门[1]--简介
- ActiveSkin的问题和解决