Thursday, October 31, 2019

Group columns into multiple rows and Group_concate like MySQL in SQL Server



I’ve been looking for a way to show one column in multiple rows, one cell. The content of it separated by comma’s.



For example, in stead of:





ProjectID Name count
-------------------------------------
2 Technical Services 31
1 Security Services 32
7 Technical Services 32


I would like the result of my query to look like this:





Name Label
---------------------------
Technical Services 31,2
Technical Services 32,7
Security Services 32,1


I also want the result of my query to look like this: (like Group_Concate in MySQL)





Name Label
-------------------------------
Security Services 32,1
Technical Services 31,2: 32,7

Answer



Try this:



SELECT  Name, 
CAST(count AS VARCHAR(10)) + ',' + CAST(ProjectID AS VARCHAR(10))

AS Label FROM table1


Result




NAME LABEL
----------------------------
Security Services 32,1
Technical Services 32,7

Technical Services 31,2




If you want to group by Name (Something like Group_Concate in MySQL) there is no any method for it in SQL Server. It's just a logic behind it.
So try this:



SELECT  * FROM    (
SELECT DISTINCT Name
FROM table1

) table2
CROSS APPLY
(SELECT CASE ROW_NUMBER()
OVER(ORDER BY ProjectId)
WHEN 1 THEN '' ELSE ': ' END +
(CAST(table3.count AS VARCHAR(10)) + ','
+ CAST(table3.ProjectID AS VARCHAR(10)) )
FROM table1 table3
WHERE table3.Name = table2.Name
ORDER BY ProjectID

FOR XML PATH ('')
) table3(Label)


So the result will be




NAME LABEL
--------------------------------
Security Services 32,1

Technical Services 31,2: 32,7



No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...