如果SQL中的语句怎么做呢

时间:2017-04-24 13:26:48

标签: sql if-statement

我在Tableau中运行了if语句(如下所示)。我需要把它变成SQl - 我已经尝试了很多不同的case语句,但它们都会出错。

有人可以建议我这样做吗?

    IF LEN(REPLACE([postcode]," ","")) = 7 THEN LEFT(REPLACE([postcode]," ",""),4)+" "+RIGHT(REPLACE([postcode]," ",""),3)
ELSEIF LEN(REPLACE([postcode]," ","")) = 6 THEN LEFT(REPLACE([postcode]," ",""),3)+" "+RIGHT(REPLACE([postcode]," ",""),3)
ELSEIF LEN(REPLACE([postcode]," ","")) = 5 THEN LEFT(REPLACE([postcode]," ",""),2)+" "+RIGHT(REPLACE([postcode]," ",""),3)
END

3 个答案:

答案 0 :(得分:0)

尝试使用它:

SELECT
  CASE
    WHEN LEN(REPLACE([postcode],' ','')) = 7
    THEN LEFT(REPLACE([postcode],' ',''),4)+' '+RIGHT(REPLACE([postcode],' ',''),3)
    WHEN LEN(REPLACE([postcode],' ','')) = 6
    THEN LEFT(REPLACE([postcode],' ',''),3)+' '+RIGHT(REPLACE([postcode],' ',''),3)
    WHEN LEN(REPLACE([postcode],' ','')) = 5
    THEN LEFT(REPLACE([postcode],' ',''),2)+' '+RIGHT(REPLACE([postcode],' ',''),3)
    ELSE 'ERROR'
  END
FROM YOUR_TABLE

答案 1 :(得分:0)

您可以通过IF替换语句中的CASE WHEN 以及ELSEIF

所有WHEN

但您可以将其简化为:

CASE 
WHEN LEN(REPLACE([POSTCODE]," ","")) IN (5,6,7) THEN REPLACE ([POSTCODE]," ","")
ELSE NULL
END

自f.e。 “ABC”+“DEF”=“ABCDEF”=“ABC DEF”没有空格。

答案 2 :(得分:0)

正如OP在一些查询后所说的那样,他在Hadoop上使用Hive - 而不是普通的SQL。

所以 - 也许 - 这可以让你开始:https://de.hortonworks.com/blog/hive-cheat-sheet-for-sql-users/