TSQL- csv for a column and not for the rest

前端 未结 3 1546
说谎
说谎 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:37

    Sample Data

    DECLARE @Table1  TABLE 
        (COL1 varchar(3), COL2 int, COL3 int, COL4 varchar(6))
    ;
    
    INSERT INTO @Table1
        (COL1, COL2, COL3, COL4)
    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')
    ;
    

    Script :

    SELECT   COL1 = STUFF(
                 (SELECT ',' + COL1 
                  FROM @Table1 t1
                  WHERE t1.COL2 = t2.COL2
                  FOR XML PATH (''))
                 , 1, 1, ''),COL2, COL3, COL4 from @Table1 t2
    group by COL2, COL3, COL4;
    

提交回复
热议问题