如何在SQL中查找计算百分比列的SUM

时间:2012-10-26 16:46:42

标签: sql sql-server sql-server-2008

我有一个计算百分比的列,就像这样

Convert(decimal(5,2),(PatCount*100)/@PatientCount) as Per

现在我想要上面计算的百分比的总和。所以我试着这样做,

,SUM(Convert(decimal(5,2),(PatCount*100)/@PatientCount)) as pa

但我没有提出所需的结果。对于前

Per %    Total %
6.00     6.00
7.00     7.00
85.00    85.00

我想将总Col打印为98%。请有人帮助我。

3 个答案:

答案 0 :(得分:3)

试试这个

SQL FIDDLE Example

select
    cast(PatCount * 100 / @PatientCount as decimal(5,2)) as Per,
    sum(cast(PatCount * 100 / @PatientCount as decimal(5,2))) over() as Total
from Patients as P

答案 1 :(得分:0)

要使用的总和,您将需要GROUPBY,然后总和超过该组。

最简单的方法是在单独的查询中执行此操作。可能有一种方法可以使用子查询执行此操作,或者您可以查看累积总和:Create a Cumulative Sum Column in MySQL

答案 2 :(得分:0)

您有一些选择,但使用CROSS APPLY应具有相当不错的性能特征。

;WITH q AS (
  SELECT SUM(CONVERT(decimal(5,2),(PatCount*100)/@PatientCount)) as Per
  FROM   YourTable
)
SELECT CONVERT(decimal(5,2),(PatCount*100)/@PatientCount) as Per
       , q.Per
FROM   YourTable
       CROSS APPLY q

或者甚至更好(阅读)

;WITH q AS (
  SELECT CONVERT(decimal(5,2),(PatCount*100)/@PatientCount) as Per
  FROM   YourTable
)
SELECT q.Per, qtot.PerTot
FROM   q CROSS APPLY (SELECT SUM(Per) as PerTot FROM q) qtot