'Summarize aggregations into friendly text
This is my table in SQL Server :
number grade weight
--------------------------
1 A 185
2 A 179
3 C 191
4 C 192
5 C 193
6 A 194
7 A 196
8 A 188
9 A 187
10 A 200
11 B 201
12 B 202
13 B 203
14 B 191
15 B 187
and I want this output in SQL Server (return this Text with Query not function):
Count of A : 7 , Sum of A : 1329 - Count of B : 5 , Sum of B : 984 - Count of C : 3 , Sum of C : 576
Does anyone know how I can do this?
Solution 1:[1]
;with flat_cte as (
select
sum(iif(grade='A', 1, 0)) CountA,
sum(iif(grade='A', weight, 0)) SumA,
sum(iif(grade='B', 1, 0)) CountB,
sum(iif(grade='B', weight, 0)) SumB,
sum(iif(grade='C', 1, 0)) CountC,
sum(iif(grade='C', weight, 0)) SumB
from
MyTable)
select
(concat('[Count of A : ]', cast(CountA as varchar(9)), ' , ',
'[Sum of A : ]', cast(SumA as varchar(9)), ' - ',
'[Count of B : ]', cast(CountB as varchar(9)), ' , ',
'[Sum of B : ]', cast(SumB as varchar(9)), ' - ',
'[Count of C : ]', cast(CountC as varchar(9)), ' , ',
'[Sum of C : ]', cast(SumC as varchar(9)))
from flat_cte;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
