2016-07-08 103 views
0

我的數據看起來像這樣,我不知道如何獲得列「想要」。我嘗試過各種保留,滯後和總和函數的組合,但遺憾的是沒有成功。總結兩列之間的行

month quantity1 quantity2 want 
1  a   x   x+sum(b to l) 
2  b   y   sum(x to y)+sum(c to l) 
3  c   z   sum(x to z)+sum(d to l) 
4  d  
5  e  
6  f  
7  g  
8  h  
9  i  
10  j  
11  k  
12  l  

謝謝你的任何幫助,在這個問題上

回答

2

是很方便的總結數量1,然後存儲值,以宏變量。使用多餘的'數據示例:

proc sql; 
    select sum(qty1) into:sum_qty1 from temp; 
quit; 

data want; 
    set temp; 
    value1+qty1; 
    value2+qty2; 
    want=value2+&sum_qty1-value1; 
    if missing(qty2) then want=.; 
    drop value:; 
run; 
1

您可能能夠做到這一步,但下面產生兩個期望的結果。第一步驟是計算相關quantity1值的總和,而第二個是將它們添加到相關quantity2值的總和:

data temp; 
    input month qty1 qty2; 
    datalines; 
     1 1 100 
     2 1 100 
     3 1 100 
     4 1 . 
     5 1 . 
     6 1 . 
     7 1 . 
     8 1 . 
     9 1 . 
     10 1 . 
     11 1 . 
     12 1 . 
    ; 
run; 

proc sql; 
    create table qty1_sums as select distinct 
     a.*, sum(b.qty1) as qty1_sums 
     from temp as a 
     left join temp as b 
     on a.month < b.month 
     group by a.month; 

    create table want as select distinct 
     a.*, 
     case when not missing(a.qty2) then sum(a.qty1_sums, sum(b.qty2)) end as want 
     from qty1_sums as a 
     left join temp as b 
     on a.month >= b.month 
     group by a.month; 
quit; 
1

聽起來像「滾動12個月總和」。如果是這樣,使用不同的數據結構(不是2個變量,而是24行1變量)要容易得多。那麼您就擁有了所有的ETS工具,或者是SQL或SAS數據步驟中的簡單流程。

如果你不能/不會重構你的數據,那麼你可以通過將數據加載到臨時數組(或散列表,但對於新手來說數組更簡單)來做到這一點。這使您可以直接訪問整個事情。例如:

data have; 
    do month = 1 to 12; 
    q_2014 = rand('Uniform')*10+500+month*5; 
    q_2015 = rand('Uniform')*10+550+month*5; 
    output; 
    end; 
run; 

data want; 
    array q2014[12] _temporary_;  *temporary array to hold data; 
    array q2015[12] _temporary_; 
    if _n_=1 then do;     *load data into temporary arrays; 
    do _n = 1 to n_data; 
     set have point=_n nobs=n_data; 
     q2014[_n] = q_2014; 
     q2015[_n] = q_2015; 
    end; 
    end; 
    set have; 
    do _i = 1 to _n_;       *grab the this_year data; 
    q_rolling12 = sum(q_rolling12,q2015[_i]); 
    end; 
    do _j = _n_+1 to n_data; 
    q_rolling12 = sum(q_rolling12,q2014[_j]);*grab the last_year data; 
    end; 
run;