gpt4 book ai didi

数据透视表中括号中的 SQL Server 2005 百分比

转载 作者:行者123 更新时间:2023-12-04 18:17:07 25 4
gpt4 key购买 nike

这是来自 here 的后续问题.
我有一些输出并且能够添加一个总列,但现在我需要使用该列来添加这样的百分比:

| LESSONID     RESPONSE COUNT-> | 0       | 1       | 2       | 3       | 4       | N |
---------------------------------------------------------------------------------------
|lesson1 | 1 (20%) | 1 (20%) | 1 (20%) | 1 (20%) | 1 (20%) | 5 |
|lesson2 | 1 (20%) | 1 (20%) | 1 (20%) | 2 (40%) | 0 | 5 |
|lesson3 | 1 (20%) | 1 (20%) | 0 | 3 (60%) | 0 | 5 |
|lesson4 | 0 | 1 (20%) | 4 (80%) | 0 | 0 | 5 |
|lesson5 | 0 | 5 (100%)| 0 | 0 | 0 | 5 |

我在这里找到了一些帮助,但无法将它们全部融合在一起。

Here is what I have so far

*我也在 SQL Server 2005 上,这在 SQLFiddle 中没有表示

最佳答案

您可以像处理任何其他查询一样格式化数据透视查询的结果。因此,您可以将百分比连接到其各自的来源。 Here is a SQL FIDDLE .

SELECT RC.lessonid AS 'lessonid     response count->'
, convert (varchar(20), isnull([0], 0))
+ isnull (' ('
-- As both numbers are integers don't forget to cast one of them into double
-- If you dislike * 100 format or want more precise result.
+ convert (varchar(20), [0] * 100 / RCN.N)
+ '%)', '') as [0]
, convert (varchar(20), isnull([1], 0))
+ isnull (' ('
+ convert (varchar(20), [1] * 100 / RCN.N)
+ '%)', '') as [1]
, convert (varchar(20), isnull([2], 0))
+ isnull (' ('
+ convert (varchar(20), [2] * 100 / RCN.N)
+ '%)', '') as [2]
, convert (varchar(20), isnull([3], 0))
+ isnull (' ('
+ convert (varchar(20), [3] * 100 / RCN.N)
+ '%)', '') as [3]
, convert (varchar(20), isnull([4], 0))
+ isnull (' ('
+ convert (varchar(20), [4] * 100 / RCN.N)
+ '%)', '') as [4]
,RCN.N
FROM (
SELECT lessonid
,response
,count(response) AS respcnt
FROM tblRChoices
GROUP BY lessonid
,response
) TableResponseCount
PIVOT(SUM(respcnt) FOR response IN (
[0]
,[1]
,[2]
,[3]
,[4]
)) RC
JOIN (SELECT lessonid, count(lessonid) as N FROM tblRChoices GROUP BY lessonid) RCN
ON RC.lessonid = RCN.lessonid

关于数据透视表中括号中的 SQL Server 2005 百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11465666/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com