使用Rolling Sub Totals和Percentages查询

时间:2017-02-13 12:04:57

标签: sql-server tsql

我有以下查询:

select
    DrugName,
    DrugCategoryName,
    count(*) as Count,,
    'Percentage of Total' as Percentage
from
    Visit V
Inner Join Drug D on
    V.DrugID = D.DrugID
Inner Join DrugCategory DC on
    D.DrugCategoryID = DC.DrugCategoryID
where
    V.StartDate >='01 Feb 2017' and V.EndDate < '01 Mar 2017'
group by
    DrugName, DrugCategoryName

给出了以下结果:

enter image description here

我需要获得的是获得如下结果:

0

按类别划分的子总计,并显示总计的百分比。

如果不保留光标或其他类型的循环,我怎么能完成这项工作?

1 个答案:

答案 0 :(得分:3)

您可以使用窗口函数计算比率(如果您真的需要“百分比”,则乘以100)。

您可以使用GROUPING SETS计算小计。详细了解他们here

select DrugName, DrugCategoryName,
       count(*) as Count,
       count(*) / sum(1.0 * count(*)) over () as Percentage
from Visit V Inner Join
     Drug D on
     V.DrugID = D.DrugID Inner Join
     DrugCategory DC
     on D.DrugCategoryID = DC.DrugCategoryID
where V.StartDate >= '2017-02-01' and V.EndDate < '2017-03-01'
group by grouping sets ((DrugName, DrugCategoryName), (DrugCategoryName))

编辑:

我怀疑grouping sets和Windows函数不能很好地协同工作。那么,这个怎么样:

select DrugName, DrugCategoryName, sum(Count)
from (select DrugName, DrugCategoryName,
             count(*) as Count,
             count(*) / sum(1.0 * count(*)) over () as Percentage
      from Visit V Inner Join
           Drug D on
           V.DrugID = D.DrugID Inner Join
           DrugCategory DC
           on D.DrugCategoryID = DC.DrugCategoryID
      where V.StartDate >= '2017-02-01' and V.EndDate < '2017-03-01'
      group by grouping DrugName, DrugCategoryName
     ) vdc
group by grouping sets ( (DrugName, DrugCategoryName, Percentage), (DrugCategoryName));