【问题标题】:Find a character index in string in spark sql在spark sql中查找字符串中的字符索引
【发布时间】:2019-11-12 21:08:05
【问题描述】:

我是 SQL 人员,是 Spark SQL 的新手

我需要找到字符索引'-'在字符串中的位置,如果有,那么我需要输入字符的固定长度,否则长度为零

string name = 'john-smith'

如果 '-' 在字符位置 4 则为 10 否则长度为 0

我已经在 SQL Server 中完成,但现在需要在 Spark SQL 中完成。

select 
case 
when charindex('-', name) = 4 then 10
else 0 
end 

我在 Spark SQL 中尝试过,但没有得到结果。

select find_in_set('-',name) 

请帮忙。谢谢

【问题讨论】:

    标签: apache-spark-sql pyspark-sql databricks


    【解决方案1】:

    您可以使用如下所示的 instr 函数。 insrt 检查第二个 str 参数是否是第一个参数的一部分,如果是,则返回从 1 开始的索引。

    //first create a temporary view if you don't have one already
    df.createOrReplaceTempView("temp_table")
    
    //then use instr to check if the name contains the - char
    spark.sql("select if(instr(name, '-') = 4, 10, 0) from temp_table")
    

    if 语句的参数是:

    • instr(name, '-') = 4 条件检查
    • 10 个结果为有效条件
    • 0 错误条件的结果

    【讨论】:

    • 完美的所有排序。无需创建临时表(可能对我来说) instr 函数可以完美运行。谢谢@Alexandros。
    • 有没有办法在 pyspark 中做到这一点?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-24
    • 2013-07-15
    • 2016-02-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多