Given table Fruit
id food color price
----- ------- ------- ----
1 cherry red 0.23
2 apple red 0.65
3 apple green 0.77
4 orange orange 1.03
5 lemon yellow 1.45
6 grape green 0.10
7 grape purple 0.11
8 plum purple 0.94
SELECT color, count(id) AS 'tot' FROM Fruit GROUP BY color
yields
color tot
------ ---
green 2
orange 1
purple 2
red 2
yellow 1
this gets me close
SELECT * FROM
(
SELECT color, count(id) AS 'tot' FROM Fruit GROUP BY color
) src
pivot
(
SUM('tot')
FOR color IN ([green],[orange],[purple],[red],[yellow])
) piv
yields
green orange purple red yellow
2 1 2 2 1
but how to add a row total? Maybe an UNPIVOT ?
green orange purple red yellow total
2 1 2 2 1 8
and for the bonus round, how to achieve a 2D array? like
green orange purple red yellow total
cherry 1 1
apple 1 1 2
orange 1 1
lemon 1 1
grape 1 1 2
plum 1 1
total 2 1 2 2 1 8
And of course this only works if you have a limited, known list to hardcode.
Seems like a stored procedure with some parameters would be needed for when you don't know the colors in advance.