2012-07-19 35 views
0

我有一個通訊錄,包括時間每個聯繫人住在附近的長度:總和(情況會導致不正確的

ID First_Name Last_Name Neighborhood_Time 
1  John   Smith  1-2 years 
2  Mary   Jones  2-5 years 
3  Dennis  White  2-5 years 
4  Martha  Olson  5+ years 
5  Jeff   Black  5+ years 
6  Jean   Rogers  2-5 years 

我想展示的時間百分比,結果是這樣的:

One_to_2_Years Two_to_5_Years  5+_Years 
     16    50     33 

這是我使用的是什麼:

select 
sum(case when Neighborhoods_time ='1-2 years' then 1 else 0 end)*100/(select count(*) from contact) as One_to_2_Years,  
sum(case when Neighborhoods_time ='2-5 years' then 1 else 0 end)*100/(select count(*) from contact) as Two_to_6_Years, 
sum(case when Neighborhoods_time ='5+years' then 1 else 0 end)*100/(select count(*) from contact) as Six_to_10_Years 
    from dbo.contact 

這是我的結果:

One_to_2_Years Two_to_5_Years  5+_Years 
     0    0     16 
     16    33     0 
     0    16     16 

我看到每列下的數字是正確的,我有一個問題總結他們。

我錯過了什麼?

謝謝。

+1

刪除組通過。 – 2012-07-19 13:42:33

+0

你不需要在每一列使用'/(從聯繫人中選擇count(*))',因爲你已經從聯繫人中選擇了'/ count(*)AS'' – GarethD 2012-07-19 13:48:25

+0

感謝Nicola,你正確。 – Stan 2012-07-19 13:53:13

回答

0

添加組通過Neighborhoods_time

0

您的查詢的基礎上,可以產生像

select 
    Neighborhood_Time, 
    100*COUNT(*)/(Select COUNT(*) from contact) as percentvalue 
from 
    contact 
group by 
    Neighborhood_Time 

如果你想水平佈置,那麼你應該使用一個支點

select 
* 
from 
(
select 
    Neighborhood_Time, 
    100*COUNT(*)/(Select COUNT(*) from contact) as percentvalue 
from 
    contact 
group by 
    Neighborhood_Time 
) src 
PIVOT 
(SUM(percentvalue) for Neighborhood_Time in ([1-2 years],[2-5 years],[5+ years])) as pt 
相關問題