PostgreSQL:查询查找免费天数?

时间:2018-02-22 06:55:46

标签: postgresql postgresql-9.3

我有下表给出的表格。此表格显示用户从开始日期结束日期 免费/可用

enter image description here

假设

从2018-01-15到2020-02-28(yyyy-mm-dd格式),用户可以使用车辆ID = 1。在此期间,任何用户都可以租车。

我想要的是什么:

我想计算特定时期的自由日数。

此期间:2018年1月意味着(1-Jan-201831-Jan-2018)。

免费日的计算标准:

对于车辆Id = 1 - >开始日期= 2018-01-15,结束日期= 2020-02-28

2018年1月= 16天 (由于1月份的总天数为31,但我们的开始日期从车辆ID = 1的2018-01-15开始)

2018年2月= 28天(2018-01-152020-02-28之间)

2 个答案:

答案 0 :(得分:0)

您可以对这两个日期使用减号运算符和日期范围数据类型。

postgres=# select *,upper(intersection_range)-lower(intersection_range) as available_days from (select *, daterange(start_date,end_date) * daterange('2018-01-01','2018-01-31') as intersection_range from vehicle) a;
 vehicle_id | start_date |  end_date  |   intersection_range    | available_days 
------------+------------+------------+-------------------------+----------------
          1 | 2017-12-31 | 2020-02-28 | [2018-01-01,2018-01-31) |             30
          2 | 2017-11-30 | 2018-02-28 | [2018-01-01,2018-01-31) |             30
          3 | 2017-07-31 | 2019-02-28 | [2018-01-01,2018-01-31) |             30
(3 rows)

最好的问候。

答案 1 :(得分:0)

Select enddate, startdate, CASE 
      WHEN startdate<= '2017-01-01' and enddate>= '2017-01-31'  THEN ('2017-01-31'::date - '2017-01-01'::date)+1
      WHEN startdate<= '2017-01-01' and enddate< '2017-01-31' and enddate>= '2017-01-01' THEN (enddate::date - '2017-01-01') +1
      WHEN startdate> '2017-01-01' and enddate>= '2017-01-31' and startdate<= '2017-01-31'  THEN (('2017-01-31'::date - '2017-01-01'::date)+1) - EXTRACT(DAY FROM startdate::date))+1

      WHEN startdate> '2017-01-01' and enddate< '2017-01-31'  and startdate<= '2017-01-31'  and enddate>= '2017-01-01' THEN (enddate::date - startdate::date)+1
       end 
      as td  from table1
相关问题