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

五迷三道 提交于 2019-12-25 12:37:10

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/21463092/how-do-i-calc-a-total-row-using-a-pivot-table-without-union-rollup-or-cube

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!