用于SUM计算列的SQL语法,用于计算百分比分布

use*_*933 4 sql sql-server count sql-server-2014

我正在使用SQL Server 2014,我有以下查询运行正常:

USE MyDatabase

SELECT [Room Nights],
       COUNT([Room Nights]) AS 'Count of RN'
FROM HOLDINGS2
GROUP BY [Room Nights]
Run Code Online (Sandbox Code Playgroud)

输出如下:

Room Nights      Count of RN
 1                 3
 4                 10
 5                 6
 7                 25
Run Code Online (Sandbox Code Playgroud)

现在我想显示另一个列,它给出了百分比的分布Count of RN.因此,我的输出需要像这样:

Room Nights      Count of RN    % Distribution
     1                 3           6.8
     4                 10          22.7
     5                 6           13.6
     7                 25          56.8
Run Code Online (Sandbox Code Playgroud)

我看了下面的讨论,试图找出一个解决方案: 计算值的百分比分布.

我想出了对现有代码的以下修改,但它不起作用!我在% Distribution列中只有零.

USE MyDatabase

SELECT [Room Nights],
       COUNT([Room Nights]) AS 'Count of RN',
       CAST(COUNT([Room Nights])/(SELECT COUNT([Room Nights])*100. FROM HOLDINGS2) AS DECIMAL (9,0)) AS '% Distribution'
FROM HOLDINGS2
GROUP BY [Room Nights]
Run Code Online (Sandbox Code Playgroud)

基本上,% Distribution列应采用Count of RN并除以TOTAL Count of RN.

jpw*_*jpw 5

这可行:

select [Room Nights],
  count([Room Nights]) AS 'Count of RN',
  cast(
    (count([Room Nights])
    /
    (Select Count([Room Nights]) * 1.0 from HOLDINGS2) 
   ) * 100 as decimal(6,1)
  ) as '% Distribution'    
FROM HOLDINGS2
GROUP BY [Room Nights]
Run Code Online (Sandbox Code Playgroud)

* 1.0子查询中的强制浮点除法,并且外投限制了精度.

或者,当您使用现代版本的MSSQL时,您可以使用窗口函数:

cast(count([Room Nights])/(sum(count([Room Nights])*1.0) over ()) * 100 as decimal(6,1))
Run Code Online (Sandbox Code Playgroud)