I've managed to create a pivot table in MS SQL and I'd like to group the annual columns by the GrpID
with rollup. I understand as much that there's an aggregate clause which should be adhered to, but can't get my head around it.
SELECT *
FROM(
SELECT Descr, NameID, grpid,YE,total from appendicesgrouping
) as t
PIVOT (sum(total)
for ye in (
[2010],[2011],[2012],[2013],[2014]
)
) as PVT
WHERE grpid < 7
AND practiceiD = 2
ORDER BY nameid asc, grpid asc, descr asc
This gives the following return:
Descr|NameID|GrpID|2010|2011|2012|2013|2014|
Sale1|1 |1 |1000|1100|900 |1050|1125|
Sale2|1 |1 |500 |600 |650 |550 |525 |
Sale3|1 |1 |45 |50 |50 |45 |45 |
Cost1|1 |2 |10 |10 |10 |10 |10 |
Cost2|1 |2 |5 |5 |5 |5 |5 |
Cost10|1 |3 |10 |10 |10 |10 |10 |
Cost11|1 |3 |5 |5 |5 |5 |5 |
Ideally what I'd be after under 'Sale3' in each column would be 1545|1750|1645|1695 and so on for each change of GrpID
.
Try this. Use
SUM aggregate
in select and AddGROUP BY grpid,NameID,Descr WITH rollup
after theWhere Clause