【问题标题】:How to subtract start and end date in postgresql如何在postgresql中减去开始日期和结束日期
【发布时间】:2017-07-20 18:26:03
【问题描述】:

我的开始日期是 03-Apr-2017 和结束日期 17-May-2017,条件是我必须有 2 个答案,我应该截断 4 月的答案在 2017 年 4 月 30 日 所以我有(2017 年 4 月 30 日 - 2017 年 4 月 3 日),5 月的答案将是(2017 年 5 月 17 日 - 2017 年 5 月 1 日)。

如何在 PostgreSQL 中解决这个问题?

【问题讨论】:

  • 我认为你想要 2 行作为答案。对吗?
  • 你的问题不清楚。您是在问如何在 postgres 中对日期进行基本计算吗?
  • 好的,画这个场景对我来说有点困难,但我想要的应该是日期时间格式,而不仅仅是日期

标签: sql postgresql postgresql-9.1


【解决方案1】:

我认为这个问题的措辞可以更好,但我明白你的意思。

我对问题的解释

给定两个日期列,比如 start_dateend_date,您需要两列(可能是四列?)来描述以下两个间隔:

  1. start_date 与其月底日期之间的间隔。
  2. end_date 的月初日期与 end_date 之间的间隔。

所以,给定一个 start_date

'2017-04-03'

和一个结束日期

'2017-05-17'

您想要 start_date_to_month_end 范围

'2017-04-03 -> 2017-04-30'

month_start_to_end_date 范围

'2017-05-01 -> 2017-05-17'

我的解决方案(漂亮)

这个 postgres 查询(基于我正在使用的列名)将为您提供那些确切的结果:

select (to_char(start_date,'YYYY-MM-DD') || ' -> ' || to_char(date_trunc('month', start_date)+'1month -1day'::interval, 'YYYY-MM-DD')) as start_date_to_month_end, (to_char(date_trunc('month', end_date), 'YYYY-MM-DD') || ' -> ' || to_char(end_date, 'YYYY-MM-DD')) as month_start_to_end_date from mytable;

结果:

 start_date_to_month_end  | month_start_to_end_date
--------------------------+--------------------------
 2017-04-03 -> 2017-04-30 | 2017-05-01 -> 2017-05-17
(1 row)

每列解决方案

那是所有漂亮的格式。如果您只想要四个简单列(start_date、month_end、month_start、end_date)的代码,那么:

开始日期

start_date

月末

date_trunc('month',start_date)+'1month -1day'::interval

month_start

date_trunc('month',end_date)

结束日期

end_date

这都是假设您的日期范围不超过 1 个月的差异。如果是这样,则此代码将仅生成开始日期为该月的最后一天,以及结束日期为该月的第一天(显然)。

编辑

  • 缩短间隔语法。谢谢,Abelisto!

【讨论】:

  • 顺便说一句:'1 month -1 day'::interval
  • 谢谢——我知道有办法缩短它。 :)
  • 这不是我想要的。例如,如果开始日期和结束日期在一个月内,我可以做正常的减法。有单一的答案。我不想将这 2 个答案分成 2 个单独的字段,因为我的第一个条件是 startdate 和 enddate 在同一个月时
猜你喜欢
  • 1970-01-01
  • 2022-01-23
  • 2012-08-19
  • 1970-01-01
  • 1970-01-01
  • 2023-04-09
  • 2021-11-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多