数据表中有这样的数据:
year coures name
2005 2 str1
2005 2 str2
2005 2 str3
2005 1 zhong
2005 1 guo
想要通过查询这样表示出来:
year coures name
2005 2 str1,str2,str3
2005 1 zhong,guo
查询语句该怎么写?求教高人!!!
...全文
1303打赏收藏
求教高手一sql语句!!!!得到答案马上接贴!
数据表中有这样的数据: year coures name 20052str1 20052str2 20052str3 20051zhong 20051guo 想要通过查询这样表示出来: year coures name 2005 2 str1,str2,str3 2005 1 zhong,guo 查询语句该怎么写?求教高人!!!
create function f_str(@year int,@coures int)
returns varchar(8000)
as
begin
declare @s varchar(8000)
set @s=''
select @s=@s+','+[name] from tb where [year]=@year and coures=@coures
return stuff(@s,1,1,'')
end
go
select [year],coures,[name]=max(dbo.f_str(year,coures)) from tb
group by [year],coures
create function f_union(@year int,@coures int)
returns varchar(100)
as
begin
declare @sql varchar(100)
set @sql=''
select @sql=@sql+','+[name] from t where [year]=@year and coures=@coures
return(stuff(@sql,1,1,''))
end
go
select [year],coures,[name]=dbo.f_union([year],coures) from t group by [year],coures