3

I am aware of how to implement a simple CASE-WHEN-THEN clause in SPARK SQL using Scala. I am using Version 1.6.2. But, I need to specify AND condition on multiple columns inside the CASE-WHEN clause. How to achieve this in SPARK using Scala ?

Thanks in advance for your time and help!

Here's the SQL query that I have:

select  sd.standardizationId,
   case when sd.numberOfShares = 0 and
             isnull(sd.derivatives,0) = 0 and 
             sd.holdingTypeId not in (3,10)
        then 
             8
        else
             holdingTypeId
       end 
   as holdingTypeId 
from sd;
1

2 Answers 2

2

First read table as dataframe

val table = sqlContext.table("sd")

Then select with expression. There align syntaxt according to your database.

val result = table.selectExpr("standardizationId","case when numberOfShares = 0 and isnull(derivatives,0) = 0 and holdingTypeId not in (3,10) then 8 else holdingTypeId end as holdingTypeId")

And show result

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

2 Comments

Just curious to know, if this is working , the above query in the question also work... right? what is the difference between these two?
In first example it is used as sql which querying table and creating dataframe (If author used in same way) and it should rise parsing exception at "not in". In second example the select applied on dataframe which already created from table and there manipulations merely rises parsing exceptions depending on syntax support.
0

An alternative option, if it's wanted to avoid using the full string expression, is the following:

import org.apache.spark.sql.Column
import org.apache.spark.sql.functions._

val sd = sqlContext.table("sd")

val conditionedColumn: Column = when(
  (sd("numberOfShares") === 0) and
  (coalesce(sd("derivatives"), lit(0)) === 0) and
  (!sd("holdingTypeId").isin(Seq(3,10): _*)), 8
).otherwise(sd("holdingTypeId")).as("holdingTypeId")

val result = sd.select(sd("standardizationId"), conditionedColumn)

Comments

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.