Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge row values into a CSV (a.k.a GROUP_CONCAT for SQL Server)

Tags:

sql

sql-server

I have a table like:

EntityID   AttributeID  OptionText
5016       20           Paintings
5044       18           Female
5060       48           M
5060       48           F
5060       49           Apple
5060       49           Banana
5060       49           Cat

I want to create a view that will show:

5016    20   Paintings
5044    18   Female
5060    48   M,F
5060    49   Apple, Banana, Cat

Means The attributes values on every entity should be displayed separated by a comma.

The number of options can be varied.

Any help is appreciated!

like image 854
Moons Avatar asked Oct 13 '11 14:10

Moons


2 Answers

For each pair of EntityID, AttributeID use the XML path trick to generate the CSV

 SELECT
    M.EntityID, M.AttributeID,
    SUBSTRING(CAST(foo.bar AS varchar(8000)), 2, 7999) AS Options
FROM
    (
    SELECT DISTINCT EntityID, AttributeID
    FROM MyTable
    ) M
    CROSS APPLY
    (
    SELECT
        ',' + OptionText
    FROM
        MyTable M2
    WHERE
        M.EntityID = M2.EntityID AND M.AttributeID= M2.AttributeID
    FOR XML PATH ('')
    ) foo(bar)
like image 104
gbn Avatar answered Oct 04 '22 04:10

gbn


Try the code below (I've included all test SQL so you don't have to practice on live data). You can view a working example here: https://data.stackexchange.com/stackoverflow/q/115141/

--Set up test table
CREATE TABLE #Table1 (EntityID INT, AttributeID INT, OptionText VARCHAR(50))

INSERT INTO #Table1
SELECT  5030, 48, 'M'

INSERT INTO #Table1
SELECT  5030, 48, 'F'

--Begin actual working SQL          
SELECT      T1.EntityID,
            T1.AttributeID,
            STUFF(( SELECT    ', ' + T2.OptionText
                    FROM      #Table1 T2
                    WHERE     T2.AttributeID = T1.AttributeID
                    AND       T2.EntityID = T1.EntityID
                    FOR XML PATH('')
                  ), 1, 2, '') [Attributes]
FROM        #Table1 T1
GROUP BY    T1.EntityID, T1.AttributeID

DROP TABLE #Table1
like image 27
James Hill Avatar answered Oct 04 '22 05:10

James Hill