在SQL中具有列的结果的百分比

时间:2009-12-29 22:46:59

标签: sql select count distinct

我试图得到一个结果,显示Uniuque“原因”,它们的数量,以及它们的总数百分比。到目前为止我有

SELECT DISTINCT Reason, 
       COUNT(Reason) AS Number, 
       CAST(COUNT(Reason) AS float) / CAST(COUNT(*) AS float) AS percentage
FROM DeletedClients

然而,因为我发现COUNT(*)和COUNT(Reason)给出相同的结果。所以我的基本问题是,当我在查询中使用distinct时,如何获得总行数? 我正在使用SQL Server 2005

5 个答案:

答案 0 :(得分:5)

SELECT Reason, 
       COUNT(Reason) AS Number, 
       CAST(COUNT(Reason) AS float) / CAST(t.Total AS float) AS percentage
FROM DeletedClients,
     (SELECT COUNT(*) As Total FROM DeletedClients) t
GROUP BY Reason, Total

答案 1 :(得分:1)

使用:

SELECT x.reason,
       x.num AS NUMBER,
       CONVERT(x.num, float)/(SELECT CONVERT(COUNT(*), float) FROM DELETEDCLIENTS) AS PERCENTAGE
  FROM (SELECT t.reason,
               COUNT(*) 'num'
          FROM DELETEDCLIENTS t
      GROUP BY t.reason) x

答案 2 :(得分:0)

select reason, count(reason), 
       (count(reason)::float / (select count(reason) from reasons)::float) * 100 
       as percent 
from DeletedClients group by reason order by reason;

这就是我想出的。我以postgresql特定的方式进行了演员,但你可以根据自己的需要进行调整。你需要使用group by。我之所以添加订单只是因为我喜欢它:P

答案 3 :(得分:0)

我认为你应该使用group by:


SELECT Reason, 
       COUNT(Reason) AS Number, 
       CAST(COUNT(Reason) AS float) / CAST(COUNT(*) AS float) AS percentage
FROM DeletedClients
GROUP BY Reason

答案 4 :(得分:0)

您的查询会出现问题。没有分组(如果要返回原因列,则需要分组。

至于目标,COUNT(和其他聚合)忽略空值(如果你至少使用SQL Server),所以这应该有效:

DECLARE @TOTAL FLOAT
SELECT @TOTAL = COUNT(1)
FROM DeletedClients

SELECT DISTINCT
    Reason,
    Cnt AS Number,
    @TOTAL AS TotalRecords,
    CAST(Cnt AS float) / @TOTAL AS percentage
FROM (
    SELECT
        Reason,
        COUNT(*) AS Cnt
    FROM DeletedClients
    GROUP BY Reason
) t
GROUP BY
    Reason,
    Cnt