如何计算SQL Server 2012中每行的百分比?

时间:2015-01-15 17:43:44

标签: sql sql-server sql-server-2012

我在SQL Server 2012中有一个表,其中的数据如下:

Request_Type    Total_Count
---------------------------
   General         25
   Inquiry         15

我想在最后一列中返回计数百分比,如下所示:

Request_Type    Total_Count    Total_Percentage
--------------------------------------------------
   General         25              62.5
   Inquiry         15              37.5

我尝试了以下查询,

select 
    Request_Type, Total_Count, 
    (Total_Count* 100) / isnull(sum(Total_Count),0) as Total_Percentage 
from 
    tbl_Request

但它在Total_Percentage列中返回100。

任何关于如何实现结果的想法都将受到赞赏。

感谢。

2 个答案:

答案 0 :(得分:7)

您可以使用子查询来获取SUM(Total_Count)

SELECT Request_Type
     , Total_Count
     , (Total_Count * 100) / (SELECT SUM(Total_Count) FROM tbl_Request) AS Total_Percentage
FROM tbl_Request

答案 1 :(得分:5)

使用Sum Over()技巧获取所有行的sum,然后找到percentage。试试这个..

SELECT Request_Type,
       Total_Count,
       ( Total_Count * 100.0 ) / Sum(Total_Count)OVER()
FROM  (SELECT 'General' AS Request_Type,25        AS Total_Count
       UNION
       SELECT 'Inquiry',15)a 

<强>结果:

Request_Type    Total_Count Percentage
General         25          62.5
Inquiry         15          37.5