使用Grouped Case语句计算总计百分比

时间:2017-10-28 20:30:06

标签: sql tsql case

所以我有一个CASE声明,我已经分组了。但是,我还试图计算每个Grouped CASE结果的总数百分比。当我运行下面的命令时,它会给出

Region         Number  Percentage
West Coast     11675   0
Not West Coast 104620  0

我不明白为什么'百分比'来自' 0'。

这是代码,问题行'标记。

With [Summed Region] AS
(

SELECT 
    [State Province],

    CASE [State Province]
    WHEN 'Oregon' THEN 'West Coast'
    WHEN 'Washington' THEN 'West Coast'
    WHEN 'California' THEN 'West Coast'
    ELSE 'Not West Coast'
    END AS 'Region'

FROM 
  [WideWorldImportersDW].[Dimension].[City]
)

SELECT 
    Region,
    count(Region) AS Number,
    ---THE PROBLEM LINE IS BELOW THIS---
    count(region)/(select count(*) FROM [WideWorldImportersDW].[Dimension].
    [City]) AS Percentage


FROM 
    [Summed Region]

GROUP BY
    Region

该线的问题是什么?如果我分开两个部分,每个都返回正确的数字。但是当我把一个人分开时,我得到了' 0'。

谢谢!

1 个答案:

答案 0 :(得分:0)

它被称为整数除法。所以在某处添加一个小数:

SELECT Region, count(Region) AS Number,
       count(region) * 1.0 / (select count(*) FROM [WideWorldImportersDW].[Dimension].[City]) AS Percentage
FROM [Summed Region]
GROUP BY Region;

您也不需要子查询,因此请使用窗口函数:

SELECT Region, count(*) AS Number,
       count(*) * 1.0 / sum(count(*)) over () AS Percentage
FROM [Summed Region]
GROUP BY Region;