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

前端 未结 20 2520
无人及你
无人及你 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:05

    Install the SQLCLR Aggregates from http://groupconcat.codeplex.com

    Then you can write code like this to get the result you asked for:

    CREATE TABLE foo
    (
     id INT,
     name CHAR(1),
     Value CHAR(1)
    );
    
    INSERT  INTO dbo.foo
        (id, name, Value)
    VALUES  (1, 'A', '4'),
            (1, 'B', '8'),
            (2, 'C', '9');
    
    SELECT  id,
        dbo.GROUP_CONCAT(name + ':' + Value) AS [Column]
    FROM    dbo.foo
    GROUP BY id;
    
    0 讨论(0)
  • 2020-11-21 05:05

    Using the Stuff and for xml path operator to concatenate rows to string :Group By two columns -->

    CREATE TABLE #YourTable ([ID] INT, [Name] CHAR(1), [Value] INT)
    
    INSERT INTO #YourTable ([ID],[Name],[Value]) VALUES (1,'A',4)
    INSERT INTO #YourTable ([ID],[Name],[Value]) VALUES (1,'B',8)
    INSERT INTO #YourTable ([ID],[Name],[Value]) VALUES (1,'B',5)
    INSERT INTO #YourTable ([ID],[Name],[Value]) VALUES (2,'C',9)
    
    -- retrieve each unique id and name columns and concatonate the values into one column
    SELECT 
      [ID], 
      STUFF((
        SELECT ', ' + [Name] + ':' + CAST([Value] AS VARCHAR(MAX)) -- CONCATONATES EACH APPLICATION : VALUE SET      
        FROM #YourTable 
        WHERE (ID = Results.ID and Name = results.[name] ) 
        FOR XML PATH(''),TYPE).value('(./text())[1]','VARCHAR(MAX)')
      ,1,2,'') AS NameValues
    FROM #YourTable Results
    GROUP BY ID
    
    
    SELECT 
      [ID],[Name] , --these are acting as the group by clause
      STUFF((
        SELECT ', '+  CAST([Value] AS VARCHAR(MAX)) -- CONCATONATES THE VALUES FOR EACH ID NAME COMBINATION 
        FROM #YourTable 
        WHERE (ID = Results.ID and Name = results.[name] ) 
        FOR XML PATH(''),TYPE).value('(./text())[1]','VARCHAR(MAX)')
      ,1,2,'') AS  NameValues
    FROM #YourTable Results
    GROUP BY ID, name
    
    DROP TABLE #YourTable
    
    0 讨论(0)
提交回复
热议问题