2016-11-18 118 views
0

我沒有得到像我期望的結果。SAS每年和每個其他變量的變量的計數

這是我的數據集:

data have0; 
infile cards truncover expandtabs; 
input MC $ ET $ Date :date9. Time :time. PMC $ PXMC $ Site $ Dia MV SF; 
format date date8. Time HHMM.; 
cards; 
US000409 Meas 12Oct2015 17:26 7101 Et1 1 . 2780462.00000 1 
US000409 Meas 12Nov2016 17:33 7101 Et1 1 861.26 2780462.00000 1 
US000409 Lath 12Oct2015 17:33 7102 Et1 1 861.6 2780462.00000 1 
US01036 Meas 12Nov2016 17:26 7101 Et1 2 . 522860.00000 1 
US01036 Lath 13Oct2016 17:33 7202 Et1 2 866.68 522860.00000 1 
US01036 Meas 13Oct2015 17:33 7101 Et1 2 867.36 522860.00000 1 
US02044 Meas 13Nov2016 17:26 7202 Et1 1 . 569298.00000 1 
US02044 Lath 13Nov2015 17:33 7202 Et1 1 865.32 569298.00000 1 
US02044 Meas 14Nov2016 17:33 7202 Et1 2 865.68 569298.00000 1 
US318 Lath 14Nov2016 17:26 7101 Et2 2 . 2630856.00000 1 
US318 Meas 14Nov2016 17:33 7202 Et2 3 863.26 2630856.00000 1 
US318 Lath 14Nov2016 17:33 7202 Et2 3 863.94 2630856.00000 1 
US000409 Meas 15Nov2016 21:56 7202 Et2 3 860.98 2780462.00000 1 
US000409 Meas 15Nov2016 21:56 7203 Et2 4 861.5 2780462.00000 1 
US01036 Lath 16Nov2016 21:56 7101 Et2 4 866.64 522860.00000 1 
US01036 Meas 16Nov2016 21:56 7202 Et2 4 867.34 522860.00000 1 
US02044 Lath 17Nov2016 21:56 7203 Et2 1 865.3 569298.00000 1 
US02044 Meas 17Nov2016 21:56 7204 Et2 3 865.68 569298.00000 1 
US318 Lath 17Nov2016 21:56 7204 Et2 2 863.24 2630856.00000 1 
; 
run; 

我所試圖做的是:

PROC SQL; 
    CREATE TABLE MC_ET AS 
    SELECT t1.MC, 
      case t1.ET 
       when "Lath" then (COUNT(t1.ET)) AS COUNT_of_ET_Lath 
       when "Meas" then (COUNT(t1.ET)) AS COUNT_of_ET_Meas 
      end, 
      (year(t1.Date)) AS Year 
     FROM have0 t1 
     GROUP BY t1.MC, (CALCULATED Year); 
QUIT; 

我期待得到的結果是這樣的位置:

MC Year Count_Lath Count_Meas 
US000409 2015 1 1 
US000409 2016 1 3 
US01036 2015 0 1 
US01036 2016 2 2 
US02044 2015 1 0 
US02044 2016 1 3 
US318 2016 3 1 

我不知道在上面的代碼中如何使用case。我認爲我犯了一些錯誤。請幫助糾正。

謝謝。

回答

1

但是,如果你想做兩個這樣的計數,我有點迷失於你的解釋中,你需要將它們放在單獨的列中。在SQL情況下作爲一個開關,它的輸出總是隻有一列。

但是我不使用SAS,我使用Oracle,所以請謹慎行事。在Oracle中,字符串是用引號括起來的而不是用引號括起來的,也許你的情況也是如此。

我會建議去嘗試,而不是你的情況是:

sum(case when t1.ET='Lath' then 1 else 0 end) as count_lath, 
sum(case when t1.ET='Meas' then 1 else 0 end) as count_meas 

分組你應該確定。

試試這個,希望它有幫助。

0

是的,我明白了...謝謝... @Emil

PROC SQL; 
    CREATE TABLE MC_ET AS 
    SELECT t1.MC, (year(t1.Date)) AS Year, 
       sum(case when t1.ET='Lath' then 1 else 0 end) as Count_of_Lath, 
       sum(case when t1.ET='Meas' then 1 else 0 end) as count_of_Meas 
     FROM have t1 
     GROUP BY t1.MC, (CALCULATED Year) 
; 
QUIT;