2017-06-17 4 views
1

SASのような異なるマクロセットに対して同じコードを繰り返し、すべてのテーブルを一緒に読み込むようにしたい。私はsasの背景から来ているので、私はPyspark環境でこれを行う方法についてかなり混乱しています。どんな助けでも大歓迎です!SASのようにpysparkでマクロをループする方法はありますか?

例コードは以下である:

STEP1は:マクロ変数

lastyear_st=201615 
lastyear_end=201622 

thisyear_st=201715 
thisyear_end=201722 

STEP2定義:ループ様々なマクロ変数

介してコードを
customer_spend=sqlContext.sql(""" 
select a.customer_code, 
sum(case when a.week_id between %d and %d then a.spend else 0 end) as spend 
from tableA 
group by a.card_code 
""" 
%(lastyear_st,lastyear_end) 
(thisyear_st,thisyear_end)) 

STEP3:上記移入データセットのそれぞれを追加ベーステーブルへ

答えて

1
# macroVars are your start and end values arranged as list of list. 
# where each innner list contains start and end value 

macroVars = [[201615,201622],[201715, 201722]] 

# loop thru list of list ==> 
for start,end in macroVars: 

    # prepare query using the values of start and end 
    query = "SELECT a.customer_code,Sum(CASE\ 
    WHEN a.week_id BETWEEN {} AND {} \ 
    THEN a.spend \ 
    ELSE 0 END) \ 
    AS spend FROM tablea GROUP BY a.card_code".format(start,end) 

    # execute query 
    customer_spend = sqlContext.sql(query) 

    # depending on your base table setup use appropriate write command for example 

    customer_spend\ 
    .write.mode('append')\ 
    .parquet(os.path.join(tempfile.mkdtemp(), 'data')) 
+0

こんにちはプッシュクル、ありがとう。リスト内で文字列値を使用することはできますか?つまり、[['a'、 'b'、 'c']、[1,2、 'x]]などのようになりますか? –

+0

はい、あなたも文字列を使うことができます – Pushkr

+0

私はまた、配列から別々にマクロ変数を定義し、配列内でそれを参照することもできます:a = "" "費やし> 0、1 else else end" "[[a 、1,2]、[a、2,4]] –

関連する問題