在SQL中计算百分比表列

时间:2013-10-11 01:25:15

标签: sql

如何计算整列的百分比?目前我写的内容只给出了每一行的百分比。我只想要一行占总百分比。我想将所有值相加以计算一个百分比。

SELECT TOP 1000
       CONVERT(DECIMAL(10, 2), CAST(Passed AS DECIMAL(10, 2))
        / ( Actual ) * 100) AS Percent
FROM    Audits
WHERE   
        MONTH(TransActionDate) = MONTH(GETDATE())
GROUP BY Actual
     , Passed
      , transactiondate
ORDER BY TransActionDate DESC

1 个答案:

答案 0 :(得分:1)

尝试使用AVG()并删除GROUP BY子句中的字段:

SELECT AVG(CONVERT(DECIMAL(10, 2), CAST(Passed AS DECIMAL(10, 2))
        / ( Actual ) * 100)) AS Percent
FROM Audits
WHERE MONTH(TransActionDate) = MONTH(GETDATE())

如果您需要TOP 1000,请使用子查询:

SELECT AVG(Percent)
FROM (
    SELECT TOP 1000
       CONVERT(DECIMAL(10, 2), CAST(Passed AS DECIMAL(10, 2))
        / ( Actual ) * 100) AS Percent
    FROM Audits
    WHERE MONTH(TransActionDate) = MONTH(GETDATE())
    ORDER BY TransActionDate DESC
    ) t