求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('')
[解决办法]
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 tgroup by Col1
[解决办法]
with t as(select b.ppid,a.pid,b.name from Project ainner join ProParticipate bon 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
[解决办法]