Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 670
user3507497 Avatar asked Apr 07 '14 17:04

user3507497


People also ask

How do I combine multiple rows of data into one row?

To merge two or more rows into one, here's what you need to do: Select the range of cells where you want to merge rows. Go to the Ablebits Data tab > Merge group, click the Merge Cells arrow, and then click Merge Rows into One.

How do you join rows in SQL?

(INNER) JOIN : Returns records that have matching values in both tables. LEFT (OUTER) JOIN : Returns all records from the left table, and the matched records from the right table. RIGHT (OUTER) JOIN : Returns all records from the right table, and the matched records from the left table.


1 Answers

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
like image 127
crthompson Avatar answered Oct 04 '22 14:10

crthompson