日期:2014-05-17 浏览次数:20434 次
--实现split功能 的函数
create function f_split(@SourceSql varchar(8000),@StrSeprate varchar(10))
returns @temp table(a varchar(100))
as
begin
declare @i int
set @SourceSql=rtrim(ltrim(@SourceSql))
set @i=charindex(@StrSeprate,@SourceSql)
while @i>=1
begin
insert @temp values(left(@SourceSql,@i-1))
set @SourceSql=substring(@SourceSql,@i+1,len(@SourceSql)-@i)
set @i=charindex(@StrSeprate,@SourceSql)
end
if @SourceSql<>'\'
insert @temp values(@SourceSql)
return
end
go
--> 测试数据:[a]
if object_id('[a]') is not null drop table [a]
go
create table [a]([xueke] varchar(50),[hits] int)
insert [a]
select '数学,语文',2 union all
select '语文,英语',3 union all
select '化学,物理',4 union all
select '物理,生物',6 union all
select '化学',3
if object_id('[b]') is not null drop table [b]
go
create table [b]([xueke] varchar(50),[hits] int)
select row_number() over(order by xueke ) as rn,* into #a from a
declare @i int ,@j int ,@k varchar(10),@l int
set @i =1
select @j=max(rn) from #a
while(@i<=@j)
begin
select @k=[xueke],@l= [hits] from #a where rn =@i
insert into b select a,@l from dbo.f_split(@k,',')
set @i=@i+1
end
select xueke ,sum(hits) as hits from b group by xueke