簡體   English   中英

Pyspark:將 sql 查詢轉換為 pyspark?

[英]Pyspark: Convert sql query to pyspark?

我有一組帶有一些案例陳述的查詢。 我需要在 pyspark 中轉換相同的邏輯。

case
when appointment_date is null
then 0
--Ticket resolved without having to send a truck out
when nvl(resolution,'') in (
'CSTXCL - OK BY PHONE'
,'OK AT TIME CALLED'
,'CONFIRMED OK BY PHONE'
,'RESOLVED THROUGH FOLLOW UP'
,'OK BY PHONE CALL'
)
or nvl(resolution,'') ilike '%NO VAN ROLL%'
then 0
--Don't count truck rolls for pending or cancelled records
--...Ideally we should not count for 'created' records either...
--...but some of the Insights code "expects" truck_roll to be populated for 'created' records...
when wo_status in ('PENDING','CANCELLED')
then 0
when stype = 'install'
and (
btrim(job_task,'\"') ilike '%Disco%'
or btrim(job_task,'\"') ilike '%Reconnect%'
or btrim(job_task,'\"') ilike '%Wireless Uninstall%'
or btrim(job_task,'\"') ilike '%Remove%'
or btrim(job_task,'\"') ilike '%Retrieve%'
)
and btrim(job_task,'\"') not ilike '%[!n]Install%'
and btrim(job_task,'\"') not ilike '%[!se]Connect%'
and btrim(job_task,'\"') not ilike 'Install%'
and btrim(job_task,'\"') not ilike 'Connect%'
and btrim(job_task,'\"') not ilike '%(COPPER TO FTTH)%'
then 0
else 1
end as truck_roll

我正在處理將 SQL 代碼轉換為 PySpark 代碼並遇到一些 SQL 語句。 我不知道如何處理 pyspark 中的案例陳述? 如果有人知道如何在 pyspark 中實現相同的邏輯,將不勝感激。

您可以使用when -function(參見pyspark.sql.functions.when

因此,為了簡化您的查詢:

case
when job_task is null
then 0
when job_task = 'ABC'
then 1
else 2
end as truck_roll

將在pyspark中翻譯成以下內容

df.withColumn('truck_roll', when(df.job_task.isNull(), 0).when(df.job_task == 'ABC', 1).otherwise(2)

即你可以像上面那樣嵌套when有多個“case”,而otherwise else你使用 else 。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM