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

How to calculate percentage of each row in SQL Server 2012?

我在 SQL Server 2012 中有一个 table,数据如下:

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

我想 return 最后一列中的计数百分比,如下所示:

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

但它 return 在 Total_Percentage 列中是 100。

任何关于如何实现结果的想法都将不胜感激。

谢谢。

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

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

使用 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