2015-10-10 69 views
0

您好我有一個數據集看起來像這樣集團在子查詢SAS

Brand Category 
---------------------- 
A  1 
A  1 
A  1 
B  1 
B  1 
C  1 
A  2 
C  2 
C  2 
C  2 

,我想要得到的市場份額在每個類別中的每個品牌。比如說,A類的市場份額是3/6 = 50%。

我使用的SQL代碼

proc sql; 
    select 
    Brand, 
    count(brand)/(select count(category) from dataset group by category) as percent 
    from dataset 
    group by brand, category; 

但SAS報告

ERROR: Subquery evaluated to more than one row. 

請幫助錯誤。非常感謝!

+0

爲什麼不使用PROC FREQ? – Tom

+0

感謝您的回覆。因爲它會爲類別1和2中出現的品牌A造成問題。我使用sql是因爲它更容易計算市場集中度指數,它等於(a的百分比)^ 2 +(b的百分比)^ 2 +(百分比的c)^ 2。 – user5386338

回答

1

您需要將類別總計數合併回品牌*類別組合。如果你願意,PROC SQL會自動爲你做。

data have ; 
    input Brand $ Category $ @@; 
cards; 
A 1 A 1 A 1 B 1 B 1 C 1 A 2 C 2 C 2 C 2 
; 

proc sql; 
    select brand 
     , category 
     , nobs 
     , sum(nobs) as cat_total 
     , nobs/calculated cat_total as percent 
    from (select category,brand,count(*) as nobs 
     from have 
     group by 1,2 
     ) 
    group by category 
    order by 1,2 
; 

注:該查詢需要重新彙總彙總統計數據與原始數據。

+0

非常感謝! – user5386338

0
select count(category) from dataset group by category 

此子查詢返回多於1行。它返回每個類別的計數。但是你要一個特定類別的數量,所以用

select count(category) from dataset where category = d.category 

替換它,並確保你給datasetfrom dataset d

別名這是一個使用派生表的另一種方式,其中一個派生表包含每個計數品牌/類別,第二個表格包含每個類別的總數。

select cnt/total, t1.brand, t1.category 
from (
    select count(*) cnt, brand , category 
    from dataset 
    group by brand, category 
) t1 join (
    select count(*) total, category 
    from dataset 
    group category 
) t2 on t2.category = t1.category 
+0

非常感謝! – user5386338

0

我只是用湯姆提到的proc freq。

proc freq data = yourdata; 
table brand*category/missprint list; 
run; 

這應該給你你想要的%沒有複雜的sql編程。