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

后端 未结 3 1742
北荒
北荒 2020-11-30 10:19

I have a table like:

EntityID   AttributeID  OptionText
5016       20           Paintings
5044       18           Female
5060       48           M
5060               


        
相关标签:
3条回答
  • 2020-11-30 10:49

    I have done some tests with 3 different methods:

    http://blog.feronovak.com/2011/10/multiple-values-in-one-column-aka.html

    Hope it helps.

    0 讨论(0)
  • 2020-11-30 11:03

    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: http://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
    
    0 讨论(0)
  • 2020-11-30 11:12

    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)
    
    0 讨论(0)
提交回复
热议问题