--2。 得出课1到课5有多少种选择方法--创建一个处理函数--为了效率,所以要一个辅助表配合
select top 8000 id=identity(int,1,1) into 序数表
from syscolumns a,syscolumns b
alter table 序数表 add constraint pk_id_序数表 primary key(id)
go--处理函数
create function f_sort(
@str varchar(8000) --要排序的字符串
)returns varchar(8000)
as
begin
declare @re varchar(8000)
set @re=''
select @re=@re+','+st
from(
select top 100 percent st=substring(@str,id,charindex(',',@str+',',id)-id)
from 序数表
where id<=len(@str)+1 and charindex(',',','+@str,id)-id=0
)a order by st
return(substring(@re,2,8000))
end
go--调用这个函数实现你的统计
select 月份
,课1=count(distinct case when 课1 is null then null else dbo.f_sort(课1) end)
,课2=count(distinct case when 课2 is null then null else dbo.f_sort(课2) end)
,课3=count(distinct case when 课3 is null then null else dbo.f_sort(课3) end)
,课4=count(distinct case when 课4 is null then null else dbo.f_sort(课4) end)
,课5=count(distinct case when 课5 is null then null else dbo.f_sort(课5) end)
from 表
group by 月份
select top 8000 id=identity(int,1,1) into 序数表
from syscolumns a,syscolumns b
alter table 序数表 add constraint pk_id_序数表 primary key(id)
go--处理函数
create function f_sort(
@str varchar(8000) --要排序的字符串
)returns varchar(8000)
as
begin
declare @re varchar(8000)
set @re=''
select @re=@re+','+st
from(
select top 100 percent st=substring(@str,id,charindex(',',@str+',',id)-id)
from 序数表
where id<=len(@str)+1 and charindex(',',','+@str,id)-id=0
)a order by st
return(substring(@re,2,8000))
end
go--调用这个函数实现你的统计
select 月份
,课1=count(distinct case when 课1 is null then null else dbo.f_sort(课1) end)
,课2=count(distinct case when 课2 is null then null else dbo.f_sort(课2) end)
,课3=count(distinct case when 课3 is null then null else dbo.f_sort(课3) end)
,课4=count(distinct case when 课4 is null then null else dbo.f_sort(课4) end)
,课5=count(distinct case when 课5 is null then null else dbo.f_sort(课5) end)
from 表
group by 月份
from 表 a join(
select 月份,选课数
=case when 课1 is null then 0 else 1 end
+case when 课2 is null then 0 else 1 end
+case when 课3 is null then 0 else 1 end
+case when 课4 is null then 0 else 1 end
+case when 课5 is null then 0 else 1 end
from 表
group by 月份
)b on a.月份=b.月份 and b.选课数
=case when a.课1 is null then 0 else 1 end
+case when a.课2 is null then 0 else 1 end
+case when a.课3 is null then 0 else 1 end
+case when a.课4 is null then 0 else 1 end
+case when a.课5 is null then 0 else 1 end