where子句ORACLE的情况

时间:2019-01-09 08:19:35

标签: sql oracle case

SELECT *
FROM (
                SELECT P.PC_ID, PC.PC, P.BLOK_ID, B.BLOK, B.ID_MATERIAL, M.MATERIAL, M.NO_MATERIAL, P.START_DTTM, TO_CHAR(P.START_DTTM,'yyyy-mm-dd') DATE_PERENCANAAN
                FROM UTSG_PERENCANAAN P
                INNER JOIN UTSG_PC PC
                        ON P.PC_ID = PC.ID_PC
                INNER JOIN UTSG_BLOK B
                        ON P.BLOK_ID = B.ID_BLOK
                LEFT JOIN UTSG_MATERIAL M
                        ON B.ID_MATERIAL = M.ID_MATERIAL
                WHERE P.NO_LAMBUNG = '341'
                                AND P.LOKASI_ID = '2'
                                AND P.START_DTTM < TO_DATE('2019-01-09 23:40:52', 'yyyy-mm-dd hh24:mi:ss')
                ORDER BY P.START_DTTM DESC
)
WHERE 
    CASE
        WHEN BLOK = 'DD11'
            THEN ROWNUM <= 1
        ELSE
            THEN ROWNUM <= 2
    END

在where子句始终显示

的情况下,我有这样的查询
  

错误ORA-00905:缺少关键字

3 个答案:

答案 0 :(得分:5)

case语句中不能包含比较运算符。相反,您的where子句应类似于:

WHERE 
    rownum <= CASE WHEN BLOK = 'DD11' THEN 1
                   ELSE 2
              END

答案 1 :(得分:4)

为什么要使用大小写表达式?

WHERE (
        (BLOK = 'DD11' AND ROWNUM <= 1)
        OR 
        ROWNUM <= 2
    )

通常建议在where子句中使用“布尔逻辑”,这是一个主题为SQL WHERE clauses: Avoid CASE, use Boolean logic

的博客。

答案 2 :(得分:2)

我认为您需要将where子句替换为

((BLOK = 'DD11' and ROWNUM <= 1) or (ROWNUM <= 2))