2011-03-17 72 views
0

我有以下的表..如何在SQL Server 2005中查找百分比?

Region Product 
East  Orange 
West  Apple 
North Apple 
West  Orange 
South Banana 
West  Banana 

如何才能知道蘋果要在列的總記錄數的百分比和橙色爲各自的區域?

+0

您可以使用存儲過程來做到這一點 – 2011-03-17 14:57:46

回答

0

如果我理解正確,你要求的區域/產品的每個組合的百分比與整個表。

SELECT region, product, COUNT(*)*100.0/(SELECT COUNT(*) FROM YourTable) AS percentage 
    FROM YourTable 
    WHERE product in ('Apple','Orange') 
    GROUP BY region, product 
0
select 
    region, 
    sum(case when product in ('orange', 'apple') then 1 else 0 end)/(count(region) * 1.0) as percentage 
from 
    [insert_table_name] 
group by 
    region 
0

嘗試:

SELECT Region, Apples_and_Oranges/Total_Products AS Percent_Apples_and_Oranges 
     FROM (

    SELECT Region, SUM(CASE WHEN Product = 'Apple' OR Product = 'Orange' THEN 1 ELSE 0 END) AS Apples_and_Oranges, 
COUNT(*) AS Total_Products 
    FROM [Table] 
    GROUP BY Region 
    ) AS A