如何在没有UNION,ROLLUP或CUBE的情况下使用PIVOT表计算总行数?

编程入门 行业动态 更新时间:2024-10-23 11:30:13
本文介绍了如何在没有UNION,ROLLUP或CUBE的情况下使用PIVOT表计算总行数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

有人可以帮忙计算一下此PIVOT表底部的总行吗?

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

我知道我可以使用UNION进行操作,并有一个单独的查询来计算总数,但这将使数据库的命中率翻倍.

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.

我已经找到了使用ROLLUP和CUBE的示例,但是这些都是过时的功能,因此我不想使用它们.

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?

推荐答案

您可以使用 GROUPING SETS 以获得总计行:

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), ());

请参见带演示的SQL提琴

更多推荐

如何在没有UNION,ROLLUP或CUBE的情况下使用PIVOT表计算总行数?

本文发布于:2023-10-28 18:07:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1537382.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:行数   情况下   如何在   UNION   CUBE

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!