【问题标题】:Oracle PLSQL truncate datetime to specific hoursOracle PLSQL 将日期时间截断为特定时间
【发布时间】:2013-09-19 04:53:11
【问题描述】:

我有一个 Oracle PLSQL 代码生成日期时间戳列表,我想将它们截断到早上 7 点和晚上 7 点的特定时间,而不是一天的开始。

例如:

  • 01/03/2013 0700 变为 01/03/2013 0700
  • 01/03/2013 1235 变为 01/03/2013 0700
  • 01/03/2013 1932 变为 01/03/2013 1900
  • 02/03/2013 0612 变为 01/03/2013 1900

我的代码目前是:

 SELECT  TRUNC(TRUNC(SYSDATE,'hh') + 1/24 - (ROWNUM) / 24, 'dd')  as shift_date
 FROM widsys.times
 ORDER BY SYSDATE

谢谢

【问题讨论】:

    标签: oracle datetime plsql truncate hour


    【解决方案1】:

    没有条件:)

    Select your_date, 
      trunc(your_date - 7/24) +                       --the date
      trunc(to_char(your_date - 7/24,'hh24')/12)/2 +  --wich half of day
      7/24                                            --shift the hour
    from 
    your_table;
    

    See a fiddle.

    【讨论】:

      【解决方案2】:
      with data(time) as (
        select to_date('2013-09-19 00:00:00', 'YYYY-MM-DD HH24:MI:SS') from dual union all
        select to_date('2013-09-19 06:45:44', 'YYYY-MM-DD HH24:MI:SS') from dual union all
        select to_date('2013-09-19 08:12:25', 'YYYY-MM-DD HH24:MI:SS') from dual union all
        select to_date('2013-09-19 18:59:59', 'YYYY-MM-DD HH24:MI:SS') from dual union all
        select to_date('2013-09-19 19:00:00', 'YYYY-MM-DD HH24:MI:SS') from dual union all
        select to_date('2013-09-19 20:15:35', 'YYYY-MM-DD HH24:MI:SS') from dual union all
        select to_date('2013-09-19 23:59:59', 'YYYY-MM-DD HH24:MI:SS') from dual
      )
      select d.time,
      case
        when to_number(to_char(d.time, 'HH24')) >= 19 then
          trunc(d.time) + 19/24
        when to_number(to_char(d.time, 'HH24')) >= 7 then
          trunc(d.time) + 7/24
        else
          trunc(d.time - 1) + 19/24
      end as shift_date
      from data d
      ;
      

      【讨论】:

        【解决方案3】:

        您是否正在寻找这样的查询:

        SELECT   CASE
            WHEN TO_CHAR(your_date, 'hh24') > 12
            THEN TRUNC(your_date)+ 19/24
            ELSE TRUNC(your_date)+ 7/24
          END
        FROM your_table;
        

        【讨论】:

          猜你喜欢
          • 2015-12-12
          • 1970-01-01
          • 1970-01-01
          • 2018-04-24
          • 1970-01-01
          • 2018-04-17
          • 2017-09-30
          • 2021-06-11
          • 1970-01-01
          相关资源
          最近更新 更多