SQL中的IF / ELSE条件

时间:2013-01-11 12:04:06

标签: sql oracle

我正在尝试为PLSQL执行IF / ELSE语句,但我不确定我是否正确地执行此操作,因为它始终存在错误: IF上缺少右括号(TO_NUMBER(SUBSTR(ATTR_VALUE) ,6,2))!= TO_NUMBER(SUBSTR(ATTR_VALUE,1,2)))那么 但括号似乎与我平衡。

SELECT *
FROM
(
IF (TO_NUMBER(SUBSTR(ATTR_VALUE, 6, 2)) != TO_NUMBER(SUBSTR(ATTR_VALUE, 1, 2))) THEN
  SELECT ID, DATE, ATTR_VALUE, (TO_NUMBER(SUBSTR(ATTR_VALUE, 6, 4))-TO_NUMBER(SUBSTR(ATTR_VALUE, 1, 4))-48) DIFF
ELSE
  SELECT ID, DATE, ATTR_VALUE, (TO_NUMBER(SUBSTR(ATTR_VALUE, 6, 4))-TO_NUMBER(SUBSTR(ATTR_VALUE, 1, 4))) DIFF
END IF
FROM Table A
ORDER BY TIME
)
WHERE DIFF>26

请在这个问题上帮助我。

2 个答案:

答案 0 :(得分:5)

您应该能够使用CASE语句来获得结果:

SELECT *
FROM
(
  SELECT ID, 
    DATE, 
    ATTR_VALUE,
    CASE 
      WHEN TO_NUMBER(SUBSTR(ATTR_VALUE, 6, 2)) != TO_NUMBER(SUBSTR(ATTR_VALUE, 1, 2))
      THEN (TO_NUMBER(SUBSTR(ATTR_VALUE, 6, 4))-TO_NUMBER(SUBSTR(ATTR_VALUE, 1, 4))-48)
      ELSE (TO_NUMBER(SUBSTR(ATTR_VALUE, 6, 4))-TO_NUMBER(SUBSTR(ATTR_VALUE, 1, 4)))
    END DIFF
  FROM Table A
  ORDER BY TIME
)
WHERE DIFF>26

答案 1 :(得分:0)

您可以将查询修改为行上的内容,如下所示,

SELECT *
  FROM (SELECT ID,
               DATE,
               ATTR_VALUE,
               decode(TO_NUMBER(SUBSTR(ATTR_VALUE, 6, 2)),
                      TO_NUMBER(SUBSTR(ATTR_VALUE, 1, 2)),
                      TO_NUMBER(SUBSTR(ATTR_VALUE, 6, 4)) -
                      TO_NUMBER(SUBSTR(ATTR_VALUE, 1, 4)),
                      TO_NUMBER(SUBSTR(ATTR_VALUE, 6, 4)) -
                      TO_NUMBER(SUBSTR(ATTR_VALUE, 1, 4))) DIFF
          FROM A)
 WHERE diff > 26