求一个多行转为一行显示的sql--在线等!!!
表t1
字段 id,desc
数据:
id desc
1 aaa
1 bbb
1 ccc
2 xxx
2 yyy
想查出数据的形式:
id desc
1 aaa,bbb,ccc
2 xxx,yyy
多谢!!
[解决办法]
----------------------------------------------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2014-01-21 16:57:12
-- Version:
-- Microsoft SQL Server 2012 (SP1) - 11.0.3128.0 (X64)
--Dec 28 2012 20:23:12
--Copyright (c) Microsoft Corporation
--Enterprise Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: )
--
----------------------------------------------------------------
--> 测试数据:[t1]
if object_id('[t1]') is not null drop table [t1]
go
create table [t1]([id] int,[desc] varchar(3))
insert [t1]
select 1,'aaa' union all
select 1,'bbb' union all
select 1,'ccc' union all
select 2,'xxx' union all
select 2,'yyy'
--------------开始查询--------------------------
select a.id,
stuff((select ','+[desc] from [t1] b
where b.id=a.id
for xml path('')),1,1,'') 'desc'
from [t1] a
group by a.id
----------------结果----------------------------
/*
id desc
----------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1 aaa,bbb,ccc
2 xxx,yyy
*/
----------------------------------------------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2014-01-21 16:57:12
-- Version:
-- Microsoft SQL Server 2012 (SP1) - 11.0.3128.0 (X64)
--Dec 28 2012 20:23:12
--Copyright (c) Microsoft Corporation
--Enterprise Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: )
--
----------------------------------------------------------------
--> 测试数据:[t1]
if object_id('[t1]') is not null drop table [t1]
go
create table [t1]([id] int,[desc] varchar(3))
insert [t1]
select 1,'aaa' union all
select 1,'bbb' union all
select 1,'ccc' union all
select 2,'xxx' union all
select 2,'yyy'
--------------开始查询--------------------------
--2005
select a.id,
stuff((select ','+[desc] from [t1] b
where b.id=a.id
for xml path('')),1,1,'') 'desc'
from [t1] a
group by a.id
--2000
--创建函数
if object_id('F_Str') is not null
drop function F_Str
go
create function F_Str(@id int)
returns nvarchar(100)
as
begin
declare @S nvarchar(100)
select @S=isnull(@S+',','')+[desc] from [t1] where id=@id
return @S
end
go
Select distinct id,[desc]=dbo.F_Str(id) FROM [t1]
----------------结果----------------------------
/*
id desc
----------- ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1 aaa,bbb,ccc
2 xxx,yyy
(2 row(s) affected)
id desc
----------- ----------------------------------------------------------------------------------------------------
1 aaa,bbb,ccc
2 xxx,yyy
*/