将多行合并为一行并组合列SQL

时间:2014-04-07 17:33:18

标签: sql sql-server sql-server-2008 tsql

我正在尝试使此视图查询两个表,然后将每个程序ID汇总到一行,其中AttributeNames列中的所有AttributeNames一起

我加入了这两张桌子,并提取了适量的记录 现在我需要的部分就是将每个ProgramID的一行和所有AttributeNames一起放在每个id的AttributeNames列中。

示例:全部在一行中。

ProgramID      | AttributeNames
887            | Studydesign, Control Groups, Primary Outcomes.

这是我需要修改的SQL VIEW的图像,所以它执行此操作: enter image description here

THE QUERY:

SELECT TOP (100) PERCENT dbo.tblProgramAttributes.ProgramID,
       dbo.tblProgramAttributes.AttributeID AS PAattributeID, 
       dbo.tblAttributes.AttributeID, 
       dbo.tblAttributes.AttributeName
FROM   dbo.tblProgramAttributes INNER JOIN
       dbo.tblAttributes 
ON     dbo.tblProgramAttributes.AttributeID = dbo.tblAttributes.AttributeID
WHERE (dbo.tblProgramAttributes.AttributeID NOT LIKE '%ProgramType%')
ORDER BY dbo.tblProgramAttributes.ProgramID DESC

1 个答案:

答案 0 :(得分:13)

select ProgramId,
stuff(
(
    select ','+ [attributename]
    from Table1 
    where programid = t.programid for XML path('')

),1,1,'') as AttributeNames
from (select distinct programid 
      from Table1 )t

查看我的sql fiddle

结果

PROGRAMID   ATTRIBUTENAMES
887         Study Design,Control Groups,Primary Outcomes