when语句?

llycmphe  于 2021-05-27  发布在  Spark
关注(0)|答案(1)|浏览(331)

我想在sparksql查询中运行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) 我试过替换 is true= TRUE , = 'TRUE' 以及 is TRUE

wd2eg0qa

wd2eg0qa1#

尝试 == 是的。

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|
//+------+-----+-------------------+

相关问题