2

I have the following table

Year, Category,   CarID,  CarName,   Milage
--------------------------------------------
2012  GroupA       1     Porsche      100
2012  GroupA       2     Mercedes     200
2013  GroupA       3     Ferrari      300
2013  GroupB       4     Uno          200
2013  GroupB       5     Beetle       200

I want to output grouping on Year and Category and return the Car Names and milage as a display column

Year, Category, DisplayString
--------------------------------------------
2012  GroupA    Mercedes (200km), Porsche (100km)  
2013  GroupA    Ferrari (300km)
2013  GroupB    Beetle (200km), Uno (200km)

I am trying to combine a columns to comma delimited string with a group by as well as more than one type column concatenated but I'm not sure how to proceed. I'm using SQL Server 2012.

Community
  • 1
  • 1
dev2go
  • 1,539
  • 3
  • 13
  • 15

2 Answers2

3
Select A.*
      ,DistplayString = (Select Stuff((Select Distinct concat(', ',CarName,' (',Milage,'km)') 
                                        From  YourTable 
                                        Where Year=A.Year and Category=A.Category 
                                        For XML Path ('')),1,2,'') )
 From (Select Distinct Year, Category From YourTable) A

Returns (Thanks to Alan's Table Variable +1)

Year    Category    DistplayString
2012    GroupA      Mercedes (200km), Porsche (100km)
2013    GroupA      Ferrari (300km)
2013    GroupB      Beetle (200km), Uno (200km)
John Cappelletti
  • 79,615
  • 7
  • 44
  • 66
2

John beat me to it. This is pretty much the same solution under the hood.

-- Your Sample Data
DECLARE @yourtable TABLE 
(
  [year]   smallint, 
  category varchar(10), 
  CarID    int, 
  CarName  varchar(20), 
  Milage   int
);

INSERT @yourtable
VALUES 
(2012,'GroupA',1,'Porsche',  100),
(2012,'GroupA',2,'Mercedes', 200),
(2013,'GroupA',3,'Ferrari',  300),
(2013,'GroupB',4,'Uno',      200),
(2013,'GroupB',5,'Beetle',   200);

-- Solution
SELECT 
  [Year], 
  Category, 
  DisplayString = 
  STUFF
  ((
    SELECT CONCAT(', ', Carname, ' (', milage, 'km)')
    FROM @yourtable i WHERE o.[year] = i.[year] AND o.category = i.category
    FOR XML PATH('')
  ),1,2,'')
FROM @yourtable o
GROUP BY [year], category;

Returns:

Year   Category   DisplayString
------ ---------- ---------------------------------
2012   GroupA     Porsche (100km), Mercedes (200km)
2013   GroupA     Ferrari (300km)
2013   GroupB     Uno (200km), Beetle (200km)
Alan Burstein
  • 7,770
  • 1
  • 15
  • 18