Skip to content
Advertisement

Summarize aggregations into friendly text

This is my table in SQL Server :

and I want this output in SQL Server (return this Text with Query not function):

Does anyone know how I can do this?

Advertisement

Answer

Modern Versions

If on SQL Server 2017 or better, you can also do it this way (and this prevents you from having to know in advance and hard-code all the possible grades A, B, C etc., which makes it harder to add D, E, and so on later):

Output

Count of A : 7 , Sum of A : 1329 – Count of B : 5 , Sum of B : 984 – Count of C : 3 , Sum of C : 576


2012, 2014, 2016

If on 2012 – 2016, you can’t use STRING_AGG(), but you can use FOR XML PATH to achieve the same thing:


2005, 2008, 2008 R2

If you’re on earlier (unsupported and ill-advised) versions (2005 – 2008 R2), you’ll just have to make changes to the latter to perform manual string concatenations (and data type handling) instead of using CONCAT().


Examples

Working dbfiddle using a table variable

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement