如何在Oracle SQL中使用SQL中的CASE语句检查特定日期

mzaanser  于 2023-05-16  发布在  Oracle
关注(0)|答案(2)|浏览(109)

我试图在OracleSQL中编写一个语句,它将根据特定字段(column 3)中的日期是否为星期一来选择昨天或最近3天的结果。

SELECT Column1, Column2, Column3 FROM Table
WHERE CASE
       WHEN To_Char(Column2, 'Day') = 'Monday'
          THEN Column3 >= (SYSDATE - Interval "3" Day)
       ELSE Column3 >= (SYSDATE - Interval "1" Day)
    END
Order by Column3 DESC;

交替地

SELECT Column1, Column2, Column3 FROM Table
WHERE Column3 >= 
    (CASE
       WHEN To_Char(Current_Date 'D') = 1
          THEN To_Char(Current_Date - 3)
       ELSE To_Char(Current_Date - 1)
    END
Order by Column3 DESC;

为了清楚起见,我有一个包含数千个条目的表,我只需要显示昨天或周末的最新结果。该代码段的目的是从column 3读取条目的日期,然后相应地显示最近3天或昨天。
解决了:最终的代码工作--

SELECT Column1, Column2, Column3 FROM The_Table
WHERE Column3 >= 
    CASE
        WHEN to_char(Current_Date, 'fmDay', 'nls_date_language = English') = 'Monday'
            THEN TRUNC(SYSDATE) - INTERVAL '3' DAY
        ELSE TRUNC(SYSDATE) - INTERVAL '1' DAY
    END
ORDER BY Column3 DESC;
gwbalxhn

gwbalxhn1#

像这样的吗

SELECT column1, column2, column3
    FROM your_table
   WHERE column3 >=
         CASE
            WHEN TO_CHAR (column2, 'fmDay', 'nls_date_language = english') = 'Monday'
            THEN
               TRUNC(SYSDATE) - INTERVAL '3' DAY
            ELSE
               TRUNC(SYSDATE) - INTERVAL '1' DAY
         END
ORDER BY column3 DESC;
  • TO_CHAR中,包括fm(否则您将得到右填充空格的值,直到最大日期名称长度)并添加语言标识符
SQL> select 'x' || to_char(sysdate + 1, 'Day') || 'x' result from dual;

RESULT
-------------
xUtorak     x

SQL> select 'x' || to_char(sysdate + 1, 'fmDay', 'nls_date_language = english') || 'x' result from dual;

RESULT
-----------
xTuesdayx
  • 截断sysdate以将其设置为 * 午夜 *;否则,你也会得到时间分量。我猜你不需要它
SQL> alter session set nls_date_format = 'dd.mm.yyyy hh24:mi:ss';

Session altered.

SQL> select sysdate - interval '3' day result1,
  2   trunc(sysdate)- interval '3' day result2
  3  from dual;

RESULT1             RESULT2
------------------- -------------------
12.05.2023 09:45:46 12.05.2023 00:00:00
z9smfwbn

z9smfwbn2#

根据this answer,检查星期几的一种独立于区域设置的方法是使用ISO周:

SELECT
   Column1,
   Column2,
   Column3
FROM Table
WHERE
   CASE
      WHEN TRUNC(SYSDATE) - TRUNC(SYSDATE, 'IW') = 0
      THEN Column3 >= (SYSDATE - Interval "3" Day)
      ELSE Column3 >= (SYSDATE - Interval "1" Day)
   END
ORDER BY Column3 DESC;

相关问题