Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to write case with when condition in spark sql using scala

SELECT c.PROCESS_ID, 
       CASE WHEN c.PAYMODE = 'M' 
           THEN 
               CASE WHEN CURRENCY = 'USD' 
                   THEN c.PREMIUM * c.RATE 
                   ELSE c.PREMIUM END * 12
           ELSE 
               CASE WHEN CURRENCY = 'USD' 
                   THEN c.PREMIUM * c.RATE 
                   ELSE c.PREMIUM END END VAlue
FROM CMM c

i want to convert sql query spark sql api how can i do?

thanks

like image 923
praveen Avatar asked May 06 '16 04:05

praveen


1 Answers

If you are looking for the way to do this using Column objects, you can do a literal translation like this:

val df: DataFrame = ...

df.select(
  col("PROCESS_ID"),
  when(col("PAYMODE") === lit("M"),
    (when(col("CURRENCY") === lit("USD"), col("PREMIUM") * col("RATE"))
    .otherwise(col("PREMIUM"))) * 12
  ).otherwise(
    when(col("CURRENCY") === lit("USD"), col("PREMIUM") * col("RATE"))
    .otherwise(col("PREMIUM"))
  )
)

Probably a cleaner way to do it, however, is to do something like:

df.withColumn(
"result",
  when(col("CURRENCY") === lit("USD"), col("PREMIUM") * col("RATE"))
    .otherwise(col("PREMIUM"))
).withColumn(
  "result",
  when(col("PAYMODE") === lit("M"), col("result") * 12)
    .otherwise(col("result"))
)

At least, the second one is a lot easier to read to me.

like image 158
David Griffin Avatar answered Nov 19 '22 04:11

David Griffin