SQL 多行合并成一行并合并列SQL
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22919259/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Multiple rows into a single row and combine column SQL
提问by user3507497
I am trying to make this view query two tables and then roll up each Program ID into one row with all the AttributeNames in the AttributeNames colum together
我试图让这个视图查询两个表,然后将每个程序 ID 与 AttributeNames 列中的所有 AttributeNames 汇总到一行中
I joined these two tables and it pulled up the proper amount of records.
Now all I need for this part would be to roll these up where I have one row per ProgramID and all the AttributeNames' together in a AttributeNames column for each id.
我加入了这两个表,它提取了适当数量的记录。
现在,这部分我需要的只是将它们汇总起来,其中每个 ProgramID 有一行,并且每个 id 的 AttributeNames 列中的所有 AttributeNames 都放在一起。
EXAMPLE: All in one row.
示例:全部在一行中。
ProgramID | AttributeNames
887 | Studydesign, Control Groups, Primary Outcomes.
Here is the image of the SQL VIEW that I need to modified so it does this:
这是我需要修改的 SQL VIEW 的图像,以便执行以下操作:
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
回答by paqogomez
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
Check out my sql fiddle
看看我的sql 小提琴
Results
结果
PROGRAMID ATTRIBUTENAMES
887 Study Design,Control Groups,Primary Outcomes