我正在嘗試在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
請幫我弄我在期待什麼?
天哪。那**將會是一個更簡單的例子。我甚至沒有想過要把我的測試打破。 ;-) –