如何把列的内容distinct后,再横向表示?不要使用@sql变量
哪位大兄弟能用一条sql语句写出来,不要使用@sql变量。小弟拜一下!
-----------------------------
比如说数据库信息:
aaaa a1 007
aaaa a1 008
aaaa a2 007
aaaa a3 009
bbbb b1 007
bbbb b2 007
bbbb b2 008
-----------------------------
我希望得到的格式:
aaaa a1,a2,a3
bbbb b1,b2
-----------------------------
------解决方案--------------------不用变量是不能解决问题的
------解决方案--------------------SQL2000的話,最好是寫function
------解决方案--------------------GO
create function fn_test(@c1 varchar(10))
returns varchar(50)
AS
begin
declare @str varchar(50)
set @str= ' '
select @str=@str+ ', '+c2 from (select distinct c1,c2 from T) a where c1=@c1
if len(@str)> 1
set @str=stuff(@str,1,1, ' ')
return @str
end
GO
select c1,dbo.fn_test(c1) as c2
from T
group by c1
------解决方案--------------------create function fmerg(@col varchar(20))
returns varchar(8000)
as
begin
declare @str varchar(8000)
set @str= ' '
select @str=@str+ ', '+cast(col2 as varchar) from t where col1=@col
group by col2
set @str=right(@str,len(@str)-1)
return(@str)
End
go
create table t(col1 varchar(20),col2 varchar(10),col3 varchar(10))
insert t select 'aaaa ', 'a1 ', '007 '
union all select 'aaaa ', 'a1 ', '008 '
union all select 'aaaa ', 'a2 ', '007 '
union all select 'aaaa ', 'a3 ', '009 '
union all select 'bbbb ', 'b1 ', '007 '
union all select 'bbbb ', 'b2 ', '007 '
union all select 'bbbb ', 'b2 ', '008 '
go
select distinct col1,col2=dbo.fmerg(col1) from t
drop table t
drop function dbo.fmerg
结果:
aaaa a1,a2,a3
bbbb b1,b2
------解决方案--------------------create table t(col1 varchar(10), col2 varchar(5),col3 varchar(5))
insert into t select 'aaaa ', 'a1 ', '007 '
insert into t select 'aaaa ', 'a1 ', '008 '
insert into t select 'aaaa ', 'a2 ', '007 '
insert into t select 'aaaa ', 'a3 ', '009 '
insert into t select 'bbbb ', 'b1 ' , '007 '
insert into t select 'bbbb ', 'b2 ', '007 '
insert into t select 'bbbb ', 'b2 ', '008 '
declare @name varchar(10)
declare @s varchar(5)
--定义表变量,去掉col2重复值
declare @tb table(col1 varchar(10),col2 varchar(100))
insert into @tb select distinct col1,col2 from t
--定义表变量,保存游标结果