2016-05-31 154 views
1

作爲一名首次查看SAS代碼的SQL開發人員,我很努力地理解我提供的一段腳本。SAS到SQL轉換

請任何人都可以解釋下面的內容,或者如果可能的話,SQL中的等價物?

* sum up the total 6 months value for customers with positive value and quantity of items; 

proc summary data=value_last6_positive nway missing; 
    var saleprice quantity; 
    class Cardid ; 
     output out = value_last6_s (drop=_type_ _freq_) 
      sum(saleprice)=saleprice 
      sum(quantity)=quantity; 
    run; 

* rank them; 

proc sort data=value_last6_s; 
    by saleprice; 
    run; 

data count; 
    set value_last6_s; 
    count=1; 
    run; 

proc sort data=count; 
    by count; 
    run; 

data count2; 
    set count; 
    by count; 
    if first.count then rank=1; 
    else rank+1; 

    if rank=<544139 then decile=10; 
    else if rank=<544139*2 then decile=9; 
    else if rank=<544139*3 then decile=8; 
    else if rank=<544139*4 then decile=7; 
    else if rank=<544139*5 then decile=6; 
    else if rank=<544139*6 then decile=5; 
    else if rank=<544139*7 then decile=4; 
    else if rank=<544139*8 then decile=3; 
    else if rank=<544139*9 then decile=2; 
    else decile=1; 

run; 

proc freq data=count2; 
    table decile; 
    run; 

proc means data=count2; 
var saleprice; 
    class decile; 
    run; 

我儘可能構建一個臨時表相當於value_last6_s具有使用CardID分組銷售數據的聚集結構(CardID, SalePrice, Quantity)了。不確定如何繼續。提前致謝。

編輯:

我的第一proc summary塊的轉換:

-- value_last6_s 
SELECT CardID, 
     SUM(SalePrice) SalePrice, 
     SUM(Quantity) Quantity 
INTO #value_last6_s 
FROM #value_last6_positive 
GROUP BY CardID 
ORDER BY SUM(SalePrice); 
+0

我不能肯定,但我認爲它總結爲客戶提供正值和物品的數量... – RQDQ

+0

@RQDQ謝謝,非常有幫助的總共6個月的值。 –

+0

對不起 - 我無法抗拒。 :-)到目前爲止,你開發了哪些SQL? – RQDQ

回答

0

的第一步只是創建一個彙總表。虛擬變量COUNT作爲常量添加,您可能不需要。需要進行排序以按總和或SALEPRICE的順序獲取值,以便可以在下一步中創建RANK變量。

create table COUNT as 
    select Cardid 
     , sum(saleprice) as saleprice 
     , sum(quantity) as quantity 
    from value_last6_positive 
    group by Cardid 
; 

下一個數據步驟是生成一個RANK變量。你不能在PROC SQL中這樣做,因爲它不包含窗口函數。你應該可以使用ROW_NUMBER()函數來做到這一點。您可以用CASE語句替換IF/THEN/ELSE鏈。

create table COUNT2 as 
select a.* 
     , row_number() over (order by saleprice) as RANK 
     , case 
     when (rank<=544139) then 10 
     when (rand<=544139*2) then 9 
     ... 
     else 1 end as DECILE 
    from COUNT a 
; 

最後的步驟是使用新的DECILE變量創建報告。

所以一個頻率報告。

select decile,count(*) as COUNT,COUNT/(count(*) over()) as PERCENT 
    from count2 
    group by 1 
    order by 1 
; 

而且手段的總結。

select decile 
    , count(saleprice) as N 
    , mean(saleprice) as Mean 
    , min(saleprice) as Min 
    , max(saleprice) as Max 
from count2 
group by 1 
order by 1 
; 
+0

謝謝,但是不是您建議的改進與我的轉換相同,但添加了'1'常量列?我正在傾入臨時表,以便逐步打破腳本的每個部分。我真的沒有這個問題,這是後來的排名,我不明白一個常數和十分位的解釋。 –

+0

你打算使用什麼樣的SQL?它是否有RANK()或ROW_NUMBER()函數,可用於替換數據步驟用於計算排名的sum語句? – Tom

+0

T-SQL,所以是 - 'RANK()在......' –