Search code examples
sql-serverpivotaggregationcuberollup

How do I calc a total row using a PIVOT table, without UNION, ROLLUP or CUBE?


Can someone help out with calculating a total row at the bottom of this PIVOT table please?

    select *, [Drug1] + [Drug2] + [Drug3] + [Drug4] + [Drug5] as [Total]
from 
        (Select [id], [drug], [Diagnosis]
            from DrugDiagnosis
        ) as ptp
        pivot 
            (count(id) 
                for drug 
                in ([Drug1], [Drug2], [Drug3], [Drug4], [Drug5]) 
            ) as PivotTable

I know I can do it with a UNION and have a separate query to calc the totals, but that will double the hit on the database.

I have found examples using ROLLUP and CUBE, but these are deprecated features so I don't want to use them.

Any other ideas, GROUPING SETS maybe?


Solution

  • You can use GROUPING SETS to get the totals row:

    select isnull(diagnosis, 'Total') Diagnosis, 
      sum([Drug1]) Drug1, sum([Drug2]) Drug2, 
      sum([Drug3]) Drug3, sum([Drug4]) Drug4, 
      sum([Drug5]) Drug5,
      sum([Drug1] + [Drug2] + [Drug3] + [Drug4] + [Drug5]) as [Total]
    from 
    (
      Select [id], [drug], [Diagnosis]
      from DrugDiagnosis
    ) as ptp
    pivot 
    (
      count(id) 
      for drug in ([Drug1], [Drug2], [Drug3], [Drug4], [Drug5]) 
    ) as PivotTable
    group by grouping sets((diagnosis), ());
    

    See SQL Fiddle with Demo