有人可以帮忙计算这个PIVOT表底部的总行吗?
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
我知道我可以使用UNION来执行此操作并使用单独的查询来计算总计,但这会使数据库的命中率翻倍。
我找到了使用ROLLUP和CUBE的示例,但这些是不推荐使用的功能,因此我不想使用它们。
还有其他想法,GROUPING SETS吗?
答案 0 :(得分:1)
您可以使用GROUPING SETS
获取总计行:
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), ());