日期:2014-05-17  浏览次数:20534 次

求sql语句,多行拼接为一行。。。

Project 项目表 字段如下,pid为主键,guid类型,pname项目名称,creDate项目创建时间,
pID pName creDate 

ProParticipate 项目负责人信息表 ,ppid为主键,guid,pid为guid类型,为外键,Project表与ProParticipate为一对多关系,
PPid Pid name  


需要查询的结果是,项目id,项目名称,负责人(多行拼接成一行)
pid pname name

------解决方案--------------------
select a.pid,pName,name
from Project as a inner join Porparticipate as b on a.pid=b.pid
group by a.pid,pName for xml path('')
------解决方案--------------------
SQL code

if not object_id('Tab') is null 
    drop table Tab 
Go 
Create table Tab([Col1] int,[Col2] nvarchar(1)) 
Insert Tab 
select 1,N'a' union all 
select 1,N'b' union all 
select 1,N'c' union all 
select 2,N'd' union all 
select 2,N'e' union all 
select 3,N'f' 
Go 

--合并表: 

--SQL2000用函数: 

if object_id('F_Str') is not null 
    drop function F_Str 
go 
create function F_Str(@Col1 int) 
returns nvarchar(100) 
as 
begin 
    declare @S nvarchar(100) 
    select @S=isnull(@S+',','')+Col2 from Tab where Col1=@Col1 
    return @S 
end 
go 
Select distinct Col1,Col2=dbo.F_Str(Col1) from Tab 

go 

--2005 xml 
select 
    Col1, 
    Col2=stuff((select ','+ltrim(Col2)
                    from Tab  
                    where Col1=t.Col1 for xml path('')), 1, 1, '') 
from Tab  AS t
group by Col1

------解决方案--------------------
SQL code

with t 
as
(
select b.ppid,a.pid,b.name 
from Project a
inner join ProParticipate b
on a.pid=b.pid
)
select PPid,Pid,
name=stuff((select ','+ltrim(name) from t b where a.pid=b.pid for xml path('')), 1, 1, '') 
from t a

------解决方案--------------------
探讨

谢谢大家了,已经出来了。。


http://blog.csdn.net/rolamao/article/details/7745972

------解决方案--------------------
姐姐你又来蹭分了
探讨
引用:

谢谢大家了,已经出来了。。


http://blog.csdn.net/rolamao/article/details/7745972


http://blog.csdn.net/travylee/article/details/7724016