I’m busy creating a report and am stuck with how to structure the final query. I have a sub-query that returns the following result set
I need the final query result to look like this:
I know I can get there with an over engineered query, but would rather do it the right way, while also learning something new. Would really appreciate any help or suggestions. Thanks
PS Using Microsoft SQL Server 2014
Advertisement
Answer
Here is a sample of code that should do what you are expecting it to do.
CREATE TABLE #T ( AircontractIDFK INT ,DepCity CHAR(3) ,SeatsHeld INT ) INSERT INTO #T( AircontractIDFK ,DepCity ,SeatsHeld ) SELECT AircontractIDFK ,DepCity ,SeatsHeld FROM (VALUES (1175, 'JFK', 29) ,(4385, 'CLT', 27) ,(4385, 'CVG', 2) ,(4389, 'ORD', 7) ,(4389, 'ORD', 24)) AS T (AircontractIDFK, DepCity, SeatsHeld) ;WITH CTE_T AS( SELECT AircontractIDFK ,DepCity ,SUM(SeatsHeld) AS SeatsHeld FROM #T GROUP BY AircontractIDFK ,DepCity ) SELECT * ,STUFF((SELECT ',' + ST.DepCity + '(' + CAST(ST.SeatsHeld AS VARCHAR(10)) + ')' FROM CTE_T ST WHERE ST.AircontractIDFK = T.AircontractIDFK FOR XML PATH('')), 1,1,'') FROM CTE_T T