计算SQL SERVER中列的整数百分比?

时间:2015-04-10 06:57:33

标签: sql-server

我刚刚开始尝试如何计算行的百分比。这是我写的代码。

SELECT DISTINCT
ServiceName
COUNT(serviceID) AS Services
FROM Tester_DW
WHERE DateToday=20150410
GROUP BY ServiceName

如何计算上述列服务的百分比,并以百分比表示整数?如果我将查询结果放在#temp表中并从#temp计算百分比,或者可以动态计算整数%的百分比,是否更容易计算代码示例的百分比?

ADDED:输出草图

ServiceName|Services| % of Total
--------------------------------
TV-cable   |  4500  |   40%
--------------------------------
Mobile BB  |  3000  |   10%
--------------------------------
MOBILE wifi|    20  |    5%
--------------------------------

4 个答案:

答案 0 :(得分:1)

很难做到正确,因为你应该处理整数百分比的总和,使其总数达到100%。

使用Largest Remainder Method

;WITH x AS 
(
    SELECT 
        ServiceName, 
        COUNT(*) * 100.0 / SUM(COUNT(*)) OVER () AS [Percent], 
        FLOOR(COUNT(*) * 100.0 / SUM(COUNT(*)) OVER ()) AS [IntPercent], 
        COUNT(*) * 100.0 / SUM(COUNT(*)) OVER () % 1 AS [Remainder]
    FROM Tester_DW
    GROUP BY ServiceName
)
SELECT ServiceName, IntPercent + CASE WHEN Priority <= Gap THEN 1 ELSE 0 END AS IntPercent
FROM
(
    SELECT *, ROW_NUMBER() OVER (ORDER BY Remainder DESC) AS Priority, 100 - SUM(IntPercent) OVER () AS Gap FROM x
) data

答案 1 :(得分:0)

Select 
    ServiceName, 
    Count(ServiceName) as Services, 
    (Count(ServiceName)* 100 / (Select Count(*) From Tester_DW)) as [% of total]
From Tester_DW
Group By ServiceName

您只需将单个服务的计数除以所有服务的数量。

答案 2 :(得分:0)

百分比是一个计数除以总体(参考)计数。您必须使用内部查询来获得总体计数:

SELECT ServiceName, COUNT(serviceID) AS Services, 
FLOOR(COUNT(serviceID) / (SELECT COUNT(serviceID) FROM Tester_DW)) AS percent
FROM Tester_DW WHERE...

根据您想要的输出(即您的引用计数是多少),您可能还必须在内部查询中添加WHERE子句(或部分内容)。

答案 3 :(得分:0)

尝试使用窗口函数:

 Create table t(id int)
 Insert into t values
(1),(1),(2)

 Select * from (Select id,
 100.0*count(*) over(partition by id)/ count(*) over() p
 from t) t
 Group by id, p