[英]How to run case when statement with spark sql?
我想在 spark sql 查詢中運行 case when 語句。
這是數據
object green
______ _____
1 true
2 false
3 true
這是查詢
%sql
select
object,
case when green is true then 'A'
when green is false then 'B'
else 'C' end as case_when_statement
from my_table
這個查詢給了我這個錯誤: mismatched input 'object' expecting <EOF>(line 3, pos 14)
我試過用= TRUE
, = 'TRUE'
替換is true
並且is TRUE
嘗試使用==
true。
spark.sql("""select
object,
case when green == true then 'A'
when green == false then 'B'
else 'C' end as case_when_statement
from tmp""").show()
//+------+-------------------+
//|object|case_when_statement|
//+------+-------------------+
//| 1| A|
//| 2| B|
//| 3| A|
//+------+-------------------+
In dataframe Api:
使用===
真
df.withColumn("case_when_statement", when(col("green") === true,lit("A")).when(col("green")===false,lit("B")).otherwise(lit("c"))).show()
//+------+-----+-------------------+
//|object|green|case_when_statement|
//+------+-----+-------------------+
//| 1| true| A|
//| 2|false| B|
//| 3| true| A|
//+------+-----+-------------------+
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.