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

后端 未结 1 1650
我寻月下人不归
我寻月下人不归 2021-02-01 21:19
SELECT c.PROCESS_ID, 
       CASE WHEN c.PAYMODE = \'M\' 
           THEN 
               CASE WHEN CURRENCY = \'USD\' 
                   THEN c.PREMIUM * c.RATE 
              


        
相关标签:
1条回答
  • 2021-02-01 22:00

    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.

    0 讨论(0)
提交回复
热议问题