21
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

3
  • Did you try registerTempTable and then sqlContext.sql("...") ? Commented May 6, 2016 at 16:26
  • hi thanks for ur reply i have done that thing but i wanna do using api so have any idea how to do it ? Commented May 9, 2016 at 4:01
  • 2
    Praveen : Can you consider accepting the @David Griffin answer. It would be pointer to other users as well.Thx Commented Sep 12, 2016 at 3:12

1 Answer 1

60

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thank u very much :)
You're welcome -- feel free to accept my answer ;-)
The cleaner way is not correct, as col("CURRENCY") === lit("USD") && col("PAYMODE") === lit("M") is resulting into col("PREMIUM") * col("RATE") * 12 as "result", which is not correct.
From my reading of the original SQL, that's the desired result. At the end of the "WHEN c.PAYMODE = 'M'" clause there's this: "END * 12", meaning when PAYMODE="M" the result gets multiplied by 12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.