TSQL- csv for a column and not for the rest

前端 未结 3 1547
说谎
说谎 2021-01-25 16:14

i need to get csv from a column but the minimum value from the rest of the columns (or any value because they are same for a group). As an example;

I have the following

3条回答
  •  遇见更好的自我
    2021-01-25 16:49

    You can do it with a sub query, like this:

    Create and populate sample table (Please save us this step in your future questions)

    DECLARE @T AS TABLE
    (
        COL1 char(3),
        COL2 int,
        COL3 int,
        COL4 char(6)
    )
    
    INSERT INTO @T VALUES
    ('ABC', 10, 35, 'GROUP1'),
    ('AQW', 10, 35, 'GROUP1'),
    ('VBN', 10, 35, 'GROUP1'),
    ('HJK', 10, 35, 'GROUP1'),
    ('DFV', 30, 25, 'GROUP2'),
    ('HYT', 30, 25, 'GROUP2'),
    ('DET', 30, 25, 'GROUP2')
    

    The query:

    SELECT DISTINCT
           STUFF(
           (
               SELECT ',' + COL1
               FROM @T
               WHERE COL2 = t.COL2
               AND COL3 = t.COL3
               AND COL4 = t.COL4
               FOR XML PATH('')
           )
           , 1, 1, '') As COL1,
           COL2,
           COL3,
           COL4
     FROM @T t
    

    Results:

    COL1                COL2    COL3    COL4
    ABC,AQW,VBN,HJK     10      35      GROUP1
    DFV,HYT,DET         30      25      GROUP2
    

提交回复
热议问题