【问题标题】:Find Occurence of Day with respect to month Oracle查找相对于月份 Oracle 的日期的出现
【发布时间】:2020-12-14 21:02:47
【问题描述】:

我想使用 Oracle RDBMS 查找特定日期相对于一个月的发生情况。

例如:比如今天是 2020 年 12 月 14 日。所以是第二个星期一。

所以我想要输出为 2。同样。

更多示例 2020 年 12 月 7 日 --> 输出应为 1(因为它是 12 月的第一个星期一) 2020 年 12 月 29 日 --> 输出应为 5(因为它是 12 月的第 5 个星期二)

【问题讨论】:

标签: sql oracle


【解决方案1】:

您可以使用case 表达式:

select (case when extract(day from sysdate) <= 7 then '1st '
             when extract(day from sysdate) <= 14 then '2nd '
             when extract(day from sysdate) <= 21 then '3rd '
             when extract(day from sysdate) <= 28 then '4th '
             else '5th '
        end) || to_char(sysdate, 'Day')
from dual;

Here 是一个 dbfiddle。

【讨论】:

    【解决方案2】:
    • 在 with 子句中,我构建了我想要的日期(例如 2020 年 12 月的整个月份),并使用 row_number 分析函数根据 YYYYMMD 格式对我的日期进行排名。我使用 D 而不是 DD,因为 D 表示星期几。我也使用 nsl_parameter (nls_date_language),因为所有国家/地区的开始日期都不相同
    • 然后我使用 to_date(lpad(rnb, 2, '0'), 'DD') 将排名列 (rnb) 转换为日期。我这样做是因为我需要使用这种日期格式 'DDth' 使 oracle 拼写出现。
    • 然后我将结果与“fmDay Month Year”格式连接
    with dates as (
    select DATE '2020-12-01' + level - 1 dt
      , row_number()over (
          partition by to_char(DATE '2020-12-01' + level - 1, 'YYYYMMD','nls_date_language = ENGLISH') 
          order by DATE '2020-12-01' + level - 1) rnb
    from dual
    connect by level <= 31
    )
    select dt
      , Initcap(to_char(to_date(lpad(rnb, 2, '0'), 'DD'), 'DDth','nls_date_language = ENGLISH'))
        ||'  '||to_char(dt, 'fmDay Month YYYY', 'nls_date_language = ENGLISH') Occurence
    from dates
    order by dt
    ;
    
    

    【讨论】:

      【解决方案3】:

      这只是一个小数学。前 7 天是每天的第一次出现,接下来的 7 天是第二次出现,依此类推。所以得到天数,例如14,减一并应用整数除法,然后再加一。

      select trunc((extract(day from sysdate) - 1) / 7) + 1 from dual;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-11-12
        • 2013-06-18
        • 2013-02-15
        • 2012-11-22
        • 2017-08-28
        • 2019-06-04
        • 2021-03-23
        • 1970-01-01
        相关资源
        最近更新 更多