SQL Server : Group by string concatenation

后端 未结 2 1992
谎友^
谎友^ 2021-01-07 04:11

I have a question. I know that has been asked before. I looked through the related questions but I could not get my SQL script to work.

Here is my query :

         


        
2条回答
  •  不思量自难忘°
    2021-01-07 04:19

    This will work -

    DECLARE @TABLE TABLE (PART_ID INT,ID INT, DESCRIPTION VARCHAR(100))
    
    INSERT INTO @TABLE 
    VALUES
    (10002   ,1182505   ,   'Tagfahrlichtschaltung')
    ,(80029   , 1182505    ,   'Bluetooth')
    ,(20004   , 1212866    ,    'Kindersitzbefestigung')
    ,(10045   ,  1212866   ,    'Lederlenkradrriegelung')
    ,(11908   ,  1257946   ,    'Airbag')
    ,(22346   , 1257946    ,    'Automatic')
    
    ;WITH SUBQUERY
    AS
    (
        SELECT ID,(CAST(PART_ID AS VARCHAR(12)) + ' : ' + DESCRIPTION) 'CONCATED'
        FROM @TABLE 
    )
    
    SELECT ID, LEFT(pre_trimmed.CONCATED , LEN(pre_trimmed.CONCATED )-1) AS LISTOFPARTS
    FROM SUBQUERY AS extern
    CROSS APPLY
    (
        SELECT CONCATED + ','
        FROM SUBQUERY AS intern
        WHERE extern.ID = intern.ID
        FOR XML PATH('')
    ) pre_trimmed (CONCATED)
    GROUP BY ID, pre_trimmed.CONCATED
    

提交回复
热议问题