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

时间:2013-01-14 20:52:32

标签: sql sql-server aggregate-functions division crosstab

我正在尝试在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;

结果:

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

我的期待:

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

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

2 个答案:

答案 0 :(得分:7)

您正在使用SQL Server。这是一个更简单的例子,可以复制这个问题:

select 1/2

SQL Server进行整数除法。

将分母替换为sum(1.0)sum(cast 1 as float)sum(1e0)而非sum(1)

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

答案 1 :(得分:1)

查询:

<强> SQLFIddleexample

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.00) -- 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

结果:

| 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 |