2013-01-14 46 views
1

我正在嘗試在SQL Server 2008 R2中執行一些交叉表。但是,如果我嘗試爲每個單元格獲取百分比,那部分是可以的,但我遇到了一個問題。SQL中的聚合函數的分類不按預期運行

這是一個蒸餾用例:一項調查,人們給他們最喜歡的顏色和他們最喜歡的水果。我想知道有多少像一個給定的水果和給定的顏色:

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 

請幫我弄我在期待什麼?

回答

5

您正在使用SQL Server。這裏是一個更復雜的例子:

select 1/2 

SQL Server做整數除法。

用分號替換sum(1.0)sum(cast 1 as float)sum(1e0)而不是sum(1)

至少與我的預期相反,SQL Server將小數點數字存儲爲數字/十進制類型(請參閱here),而不是float。固定的小數位數可能會影響後續操作。

+1

天哪。那**將會是一個更簡單的例子。我甚至沒有想過要把我的測試打破。 ;-) –

0

查詢:

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 |