Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
543 views
in Technique[技术] by (71.8m points)

sql server - Multiple rows into a single row and combine column SQL

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

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.

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: 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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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

Results

PROGRAMID   ATTRIBUTENAMES
887         Study Design,Control Groups,Primary Outcomes

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...