Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/84.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 计算百分比是与计数并列的最佳方式_Sql_Sql Server_Sql Server 2016 - Fatal编程技术网

Sql 计算百分比是与计数并列的最佳方式

Sql 计算百分比是与计数并列的最佳方式,sql,sql-server,sql-server-2016,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 Dru

我有下面的查询,我试图计算一个百分比列,但计算不正确,每行显示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,

最好的方法是使用窗口函数:

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;

谢谢你,但不幸的是,这也不起作用。每行返回0.024390243902。感谢Gordon,将1.0更改为100.0为我做到了这一点。正如约翰在下面建议的那样。