0

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

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%。请有人帮我解决这个问题。

4

3 回答 3

3

尝试这个

SQL FIDDLE 示例

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
于 2012-10-26T17:08:43.490 回答
0

要使总和起作用,您将需要一个 GROUPBY,然后总和超过该组。

最简单的是在单独的查询中执行此操作。可能有一种方法可以通过子查询来执行此操作,或者您可以查看累积和:在 MySQL 中创建累积和列

于 2012-10-26T16:55:22.577 回答
0

您有一些选择,但使用 aCROSS 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
于 2012-10-26T17:09:03.387 回答