聚合列上的聚合函数

时间:2018-01-27 14:26:18

标签: sql

我正在尝试此查询以获得如下表中的结果。

Select Building, (Total_SRs/Select(SUM(Total_SRs)) From Serveu) As '%age'
From (Select Building, Count(Building) as Total_SRs From serveu Group by Building)

Building            Total_SRs   %age
Abbey Crescent 1    83          4.36%
Abbey Crescent 2    68          3.57%
Barton House 1      12          0.63%
Botton House 1      11          0.58%
Botton House 2       3          0.16%

1 个答案:

答案 0 :(得分:0)

我会使用ANSI标准窗口函数来编写它:

Select Building, Count(*) as Total_SRs,
       count(*) * 1.0 / sum(count(*)) over () as ratio
From serveu
Group by Building;

* 1.0是因为某些数据库进行整数除法。

我更喜欢介于0和1之间的比率。如果要将值格式化为字符串,则取决于您使用的数据库。