【问题标题】:Equivalent SQL function of IFNULL and IFF in spark dataframespark数据帧中IFNULL和IFF的等效SQL函数
【发布时间】:2020-10-07 20:10:21
【问题描述】:

我正在尝试在 Spark 数据帧中使用雪花列(具有 IFFNULL 和 IFF 等功能)。我试过合并,但它不起作用。在 Spark 数据帧中是否有任何等效的功能或逻辑?

雪花 SQL:

SELECT P.Product_ID,
IFNULL(IFF(p1.ProductDesc='',NULL,p1.ProductDesc),
           IFNULL(IFF(p2.PrdDesc='',NULL,p2.PrdDesc),IFF(p3.Product_Desc='',NULL,p3.Product_Desc))
          ) AS Product_Description
FROM Product p
LEFT JOIN Product_table_1 p1 ON p1.Product_ID = p.Product_ID
LEFT JOIN Product_table_2 p2 ON p2.Product_ID = p.Product_ID
LEFT JOIN Product_table_3 p3 ON p3.Product_ID = p.Product_ID

我试过了:coalesce(p1.ProductDesc, p2.PrdDesc, p3.Product_Desc) 但它不起作用

【问题讨论】:

标签: sql dataframe apache-spark apache-spark-sql


【解决方案1】:

IIUC,你可以试试 coalesce + nullif:

nullif(expr1, expr2) - 如果 expr1 等于 expr2,则返回 null,否则返回 expr1。

例如(使用 pyspark):

df = spark.createDataFrame([(None,"","a"),("a","","b"),("",None,"c")],["desc1", "desc2", "desc3"])

df.createOrReplaceTempView("tb")

spark.sql("select *, coalesce(nullif(desc1,''), nullif(desc2,''), nullif(desc3,'')) as desc from tb").show()       
+-----+-----+-----+----+
|desc1|desc2|desc3|desc|
+-----+-----+-----+----+
| null|     |    a|   a|
|    a|     |    b|   a|
|     | null|    c|   c|
+-----+-----+-----+----+

所以对于您的任务,请使用以下内容:

coalesce(nullif(p1.ProductDesc,''), nullif(p2.PrdDesc,''), nullif(p3.Product_Desc,'')) as Product_Description

顺便说一句。您也可以将原始 SQL 中的所有 IFF 更改为 IF

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-15
    • 1970-01-01
    • 2016-09-18
    • 2018-04-10
    相关资源
    最近更新 更多