计算百分比与计数的最佳方式

时间:2016-12-18 00:56:55

标签: sql sql-server sql-server-2016

我有以下查询,我正在尝试计算百分比列,但它没有正确计算,每行显示100,这显然是不正确的。

我在这里做错了什么?我已经看到很多以不同方式计算百分比的例子,我想知道这里最好的方法是什么。

Select 
DrugName, 
Occurrences,  
(Occurrences / sum(Occurrences)) * 100 as Percentage
from
(
select 
D.DrugName,
count(*) as Occurrences
from
Visit V
Inner Join Drug D on 
V.DrugID = D.DrugID
where
StartDate >='01 Oct 2016' and
EndDate < '01 Jan 2017'
group by
D.DrugName
) a
group by
DrugName,

1 个答案:

答案 0 :(得分:1)

执行此操作的最佳方法是使用窗口函数:

select D.DrugName,
       count(*) as Occurrences,
       count(*) * 100.0 / sum(count(*)) over ()
from Visit V Inner Join
     Drug D 
     on V.DrugID = D.DrugID
where StartDate >= '2016-10-01' and
      EndDate < '2017-01-01'
group by D.DrugName;