SQL中的聚合函数划分不符合预期

Jam*_*son 2 sql sql-server crosstab aggregate-functions division

我正在尝试在SQL Server 2008 R2中做一些交叉表.那部分没关系,但是,如果我试图获得每个单元格的百分比,我就会遇到问题.

这是一个蒸馏用例:一项调查,人们给出他们喜欢的颜色和他们喜欢的水果.我想知道有多少像给定的水果和给定的颜色:

with survey as (
    select 'banana' fav_fruit, 'yellow' fav_color
     union select 'banana', 'red'
     union select 'apple', 'yellow'
     union select 'grape', 'red'
     union select 'apple', 'blue'
     union select 'orange', 'purple'
     union select 'pomegranate', 'green'
)
select
    s.fav_color, 
    sum(case 
          when s.fav_fruit = 'banana' then 1
          else 0
        end) as banana, 
    sum(case 
           when s.fav_fruit = 'banana' then 1
           else 0
         end) / sum(1)   -- why does division always yield 0? "+", "-", and "*" all behave as expected.
         * 100 as banana_pct,
     sum(1) as total
from 
    survey s
group by
    s.fav_color;
Run Code Online (Sandbox Code Playgroud)

结果:

fav_color   banana banana_pct  total
------------------------------------
blue        0      0            1
green       0      0            1
purple      0      0            1
red         1      0            2
yellow      1      0            2
Run Code Online (Sandbox Code Playgroud)

我期待的是:

fav_color   banana banana_pct  total
------------------------------------
blue        0      0           1
green       0      0           1
purple      0      0           1
red         1      50          2
yellow      1      50          2
Run Code Online (Sandbox Code Playgroud)

请帮助我得到我期待的东西?

Gor*_*off 7

您正在使用SQL Server.这是一个复制问题的简单示例:

select 1/2
Run Code Online (Sandbox Code Playgroud)

SQL Server执行整数除法.

像下面这样替换分母sum(1.0)sum(cast 1 as float)sum(1e0)代替sum(1).

与我的期望至少相反,SQL Server将带小数点的数字存储为数字/十进制类型(请参阅此处)而不是float.固定数量的小数空格可能会影响后续操作.