2

这是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 |

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

这是我到目前为止所拥有的

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

4

2 回答 2

2

您可以像处理任何其他查询一样格式化数据透视查询的结果。因此,您可以将百分比连接到其各自的来源。这是一个 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
于 2012-07-13T10:02:42.140 回答
2

您可以通过将值转换为字符串然后将其连接成一个字符串来做到这一点(SQL Fiddle with Demo of it in one field)。与此类似:

SELECT RC.lessonid AS 'lessonid     response count->'
 , cast(isnull([0], 0) as varchar(10)) 
   + isnull(' (' + cast([0]*100/RCN.N as varchar(10)) + '%)', '') as [0]

但是,我的问题是您是否需要将其显示在与字符串相同的列中。你打算在前端应用程序中使用它吗?如果是这样,那么您可能需要考虑将百分比放在单独的列中,这样您仍然会将初始值作为 int。(请参阅SQL Fiddle with Demo)根据您将如何使用此数据,以这种方式执行此操作可为您提供更大的灵活性,因为这样您就不必去除百分比来获得初始值。

SELECT RC.lessonid AS 'lessonid     response count->'
  , cast(isnull([0], 0) as varchar(10))  as [0]
  , isnull(' (' + cast([0]*100/RCN.N as varchar(10)) + '%)', '') as [%_0]
于 2012-07-13T11:36:42.783 回答