【问题标题】:Oracle - complexer case statement in where-clauseOracle - where 子句中更复杂的 case 语句
【发布时间】:2026-02-18 03:00:02
【问题描述】:

在 Oracle 中,我需要设置 MYDATE 的 where 子句取决于当年的月份。 如果月份等于或大于四月,则将 MYDATE 限制为当前年份 (01.01.YEAR - 31.12.YEAR) ELSE 将 MYDATE 限制为比当前时间更早的每个日期。

如果可能的话,我需要一个纯 SQL 解决方案,而不是 PL/SQL。我试图调整我在网上和 *.com 上找到的内容,但语法错误:

SELECT text, mydate
FROM mytable
WHERE
CASE
    WHEN to_number(TO_CHAR(sysdate, 'MM')) >= 4 -- if month of current year >= april
        THEN mydate >=TRUNC(LAST_DAY(SYSDATE), 'YYYY') --beginning of current year
        AND mydate  < TRUNC(LAST_DAY(SYSDATE)+1, 'YYYY') -- end of current year
    ELSE -- if month of current year < april
        mydate < sysdate;   

有人可以帮我吗?

非常感谢您。

【问题讨论】:

    标签: oracle case where-clause


    【解决方案1】:

    您不需要CASE。在 WHERE 中只需 AND / OR 即可。

    SELECT text, mydate
    FROM mytable
    WHERE
       (     to_number(TO_CHAR(sysdate, 'MM')) >= 4 -- if month of current year >= april
         AND mydate >=TRUNC(LAST_DAY(SYSDATE), 'YYYY') --beginning of current year
         AND mydate < TRUNC(LAST_DAY(SYSDATE)+1, 'YYYY') -- end of current year
       ) OR (
             to_number(TO_CHAR(sysdate, 'MM')) < 4 
        AND  mydate < sysdate)
       );
    

    【讨论】: