您可以对数据透视表中的行和/或列进行小计吗?
我有一组输出数据透视表的查询。是否可以获得数据透视表的行和/或列小计?
我从中选择的表看起来像这样
Site FormID Present
Site 1 Form A Yes
Site 1 Form B Yes
Site 1 Form D Yes
等...
我的数据透视表查询是这样的
SELECT *
FROM (SELECT Site, COUNT(FormID) AS NumberOfForms,FormID
FROM @CRFCount WHERE Present='Yes'
GROUP BY Site, FormID) d
PIVOT
(SUM(NumberOfForms)
FOR [Site] IN ([Site 1], [Site 2], [Site 3])
) AS p;
但我真的希望它产生这样的结果(当然这对我来说并不完全)
FormID Site 1 Site 2 Site 3 Total
Form A 8 8 15 31
Form B 14 4 NULL 18
Form C 14 NULL NULL 14
Form D 15 3 16 34
Form E 12 4 NULL 16
Form F 14 5 5 24
Form G 14 8 6 28
Form H 22 10 15 47
Form I 15 10 16 41
Form J 15 5 16 36
Total 143 57 89 289
感谢您的帮助!
-大学教师
I have a set of queries that outputs a pivot table. Is it possible to obtain row and/or column subtotals for a pivot table ?
My table I am selecting from looks like this
Site FormID Present
Site 1 Form A Yes
Site 1 Form B Yes
Site 1 Form D Yes
etc...
My pivot table query is this
SELECT *
FROM (SELECT Site, COUNT(FormID) AS NumberOfForms,FormID
FROM @CRFCount WHERE Present='Yes'
GROUP BY Site, FormID) d
PIVOT
(SUM(NumberOfForms)
FOR [Site] IN ([Site 1], [Site 2], [Site 3])
) AS p;
But I really want it to result in this (which of course it does not total for me)
FormID Site 1 Site 2 Site 3 Total
Form A 8 8 15 31
Form B 14 4 NULL 18
Form C 14 NULL NULL 14
Form D 15 3 16 34
Form E 12 4 NULL 16
Form F 14 5 5 24
Form G 14 8 6 28
Form H 22 10 15 47
Form I 15 10 16 41
Form J 15 5 16 36
Total 143 57 89 289
Thanks for your assistance !
-Don
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
注意:如果您使用的是 SQL Server 2005,则需要更改此设置:
尝试
SE 数据
Note: If you are using SQL Server 2005 you need to change this:
to
Try on SE Data
试试这个(未测试):
Try this (not tested):
示例表
1.行和列总计
您可以使用
CUBE
获取旋转时的行和列总计。有关CUBE
的更多信息此处。2.仅行总计
您可以使用
ROLLUP
获取行总计。3.仅列总计
将
GROUP BY [SITE],FORMID
更改为GROUP BY FORMID,[SITE]
现在,如果您想用零替换 null,您可以在动态枢轴之前使用以下代码。
在动态数据透视表的最外层查询中,将
@cols
变量替换为@NullToZeroCols
SAMPLE TABLE
1. Row and Column Total
You can use
CUBE
to get the row and column total on pivoting. More aboutCUBE
here.2. Row Total only
You can use
ROLLUP
to get the row total.3. Column Total only
Change
GROUP BY [SITE],FORMID
toGROUP BY FORMID,[SITE]
Now, if you want to replace null with zero, you can use the below code before dynamic pivot.
And in the out most query of dynamic pivot, replace
@cols
variable with@NullToZeroCols