【问题标题】:Reset the date portion to the first of the month while preserving the time将日期部分重置为每月的第一天,同时保留时间
【发布时间】:2018-04-06 17:10:23
【问题描述】:

有没有办法在保留时间的同时将日期部分重置为月初? 例如:

2018-01-02 23:00:00 -> 2018-01-01 23:00:00
2018-04-04 10:00:00 -> 2018-04-01 10:00:00

【问题讨论】:

  • 你所说的“trunc days”是什么意思?
  • 当然,你是对的

标签: sql oracle


【解决方案1】:
with x as (
  select to_date( '2018-01-02 23:00:00', 'yyyy-mm-dd hh24:mi:ss') as d from dual
  union all
  select to_date(  '2018-04-04 10:00:00', 'yyyy-mm-dd hh24:mi:ss') from dual
)


SELECT d, d - trunc( d ) + trunc( d, 'MM' )
FROM x;

D                   D-TRUNC(D)+TRUNC(D,
------------------- -------------------
2018-01-02 23:00:00 2018-01-01 23:00:00
2018-04-04 10:00:00 2018-04-01 10:00:00

【讨论】:

    【解决方案2】:

    是的。例如:

    select sysdate, sysdate + (trunc(sysdate, 'mm') - trunc(sysdate)) as other_date
    from   dual;
    
    SYSDATE             OTHER_DATE         
    ------------------- -------------------
    2018-04-06 10:17:47 2018-04-01 10:17:47
    

    显然,没有简单的方法可以做到这一点(您必须承认这是一个不寻常的要求)。

    等价算术:

    trunc(sysdate, 'mm') + (sysdate - trunc(sysdate))
    

    使用您认为更容易立即理解的任何一个。在这两种情况下,+ 号后面括号中的内容是两个日期的差,这是一个数字(以天为单位),可以添加到日期(+ 号之前的表达式)。

    【讨论】:

      【解决方案3】:

      另一种解决方案:

      ts - ((extract(day from ts)-1))
      

      【讨论】:

      • 对...但是其他解决方案可以很容易地概括为将时间复制到季度或年份的第一天等。使用 EXTRACT() 不容易做到。
      • @mathguy:当然,但是操作人员明确要求的第一天,无论如何这是一个不寻常的要求:-)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-01-17
      • 1970-01-01
      • 1970-01-01
      • 2021-01-24
      • 1970-01-01
      • 2014-06-29
      • 1970-01-01
      相关资源
      最近更新 更多