2

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

请帮助我得到我所期待的?

4

3 回答 3

7

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

select 1/2

SQL Server 进行整数除法。

sum(1.0)用类似或sum(cast 1 as float)sum(1e0)代替的东西替换分母sum(1)

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

于 2013-01-14T20:56:04.757 回答
1

询问:

SQLFiddle示例

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 |
于 2013-01-14T20:59:19.437 回答
0

我最近发现了 IIF 函数。它使事情变得更清洁。以上面贾斯汀的例子:

SELECT s.fav_color,
       sum( IIF(s.fav_fruit = 'banana', 1,0) AS banana,
       sum( IIF(s.fav_fruit = 'banana', 1,0) / sum(1.00) 
 * 100 AS banana_pct,
   sum(1) AS total
FROM survey s
GROUP BY s.fav_color
于 2021-10-12T14:31:16.273 回答