2013-07-11 57 views
1

,我有以下數據集:增加兩個數據的SQL查詢到一個

需要添加兩個新列 - 第一個從第2行減去第1行對每一個客戶,這樣我們就可以擁有的#「天」客戶在此之後更新的其成員 - 第二個計算時代的客戶續簽其會員#這將是剛剛從0

Row - Customer - Renew Date - Type of Renewal - Days_Since -Prev_Renewal 
1  - A  - June 10, 2010  - X       
2  - A  - May 01, 2011   - Y 
3  - B  - Jan 05, 2010   - Y 
4  - B  - Dec 10, 2010   - Z 
5  - B  - Dec 10, 2011   - X  

這裏開始的計數是,我使用的是現在的代碼。有沒有辦法將這兩組查詢合併爲一個?

data have; 
informat renew_date ANYDTDTE.; 
format renew_date DATE9.; 
infile datalines dlm='-'; 
input Row Customer $ Renew_Date Renewal_Type $; 
datalines; 
1  - A  - June 10, 2010  - X       
2  - A  - May 01, 2011   - Y 
3  - B  - Jan 05, 2010   - Y 
4  - B  - Dec 10, 2010   - Z 
5  - B  - Dec 10, 2011   - X  
;;;; 
run; 

data want; 
set have; 
by customer; 
retain prev_days; *retain the value of prev_days from one row to the next; 
if first.customer 
then 
    days_since=0; 
    *initialize days_since to zero for each customer's first record; 
else days_since=renew_date-prev_days; *otherwise set it to the difference; 
output; *output the current record; 
prev_days=renew_date; 
*now change prev_days to the renewal date so the next record has it; 
run; 

data want1; 
set have; 
by customer; 
retain prev_renewal; 
if first.customer then prev_renewal=0; 
else prev_renewal=prev_renewal+1; 
output; 
run; 

感謝

+1

建議你添加標記來指示SQL和/或你所使用的平臺是什麼方言。 – Rikalous

+0

這似乎不是SQL – logixologist

+0

使用企業指南 – learnlearn10

回答

0

這不是SQL,但是數據的步驟/ SAS基礎代碼 - SAS軟件研究所,其實際的前日期SQL的專有(4GL)語言。

關於您的程序 - 值得指出的是,在使用BY語句之前,必須對數據進行排序或索引(在這種情況下由客戶)。在這種情況下,您的數據線按正確的順序排列。

以下是你需要的組合代碼:

data want (drop=prev_days); 
    set have; 
    by customer; 
    retain prev_days; 
    if first.customer then do; 
     days_since=0; 
     prev_renewal=0; 
    end; 
    else do; 
     days_since=renew_date-prev_days; 
     prev_renewal+1; /* IMPLIED retain - special syntax */ 
    end; 
    output; 
    prev_days=renew_date; 
run;