How to use GROUP BY to concatenate strings in SQL Server?

前端 未结 20 2585
无人及你
无人及你 2020-11-21 04:33

How do I get:

id       Name       Value
1          A          4
1          B          8
2          C          9

to

id               


        
20条回答
  •  鱼传尺愫
    2020-11-21 05:01

    Don't need a cursor... a while loop is sufficient.

    ------------------------------
    -- Setup
    ------------------------------
    
    DECLARE @Source TABLE
    (
      id int,
      Name varchar(30),
      Value int
    )
    
    DECLARE @Target TABLE
    (
      id int,
      Result varchar(max) 
    )
    
    
    INSERT INTO @Source(id, Name, Value) SELECT 1, 'A', 4
    INSERT INTO @Source(id, Name, Value) SELECT 1, 'B', 8
    INSERT INTO @Source(id, Name, Value) SELECT 2, 'C', 9
    
    
    ------------------------------
    -- Technique
    ------------------------------
    
    INSERT INTO @Target (id)
    SELECT id
    FROM @Source
    GROUP BY id
    
    DECLARE @id int, @Result varchar(max)
    SET @id = (SELECT MIN(id) FROM @Target)
    
    WHILE @id is not null
    BEGIN
      SET @Result = null
    
      SELECT @Result =
        CASE
          WHEN @Result is null
          THEN ''
          ELSE @Result + ', '
        END + s.Name + ':' + convert(varchar(30),s.Value)
      FROM @Source s
      WHERE id = @id
    
      UPDATE @Target
      SET Result = @Result
      WHERE id = @id
    
      SET @id = (SELECT MIN(id) FROM @Target WHERE @id < id)
    END
    
    SELECT *
    FROM @Target
    

提交回复
热议问题