减少超出范围的时间

时间:2017-03-02 06:48:54

标签: sql postgresql

我使用PostgreSQL,如果它超出范围,我很乐意修剪日期。

首先,我喜欢将记录过滤掉。 下面的查询并不困难。 (过滤2017/3/1~2017 / 3/31)

select * from subscriptions where current_period_start_at <= date '2017/03/01' AND current_period_end_at >= date '2017/03/31'

但是,如果超出范围(2017-03-1 ~ 2017-03-31),我希望切断日期。 current_period_start_at:2017/02/25 =&gt; 2017/03/01 current_period_end_at:2017/04/02 =&gt; 2017/03/31

这是一些例子。

enter image description here

target 2016/08/05 ~ 2016/09/15 
range①  2016/07/01 ~ 2016/08/31 => 2016/08/05 ~ 2016/08/31
range②  2016/08/10 ~ 2016/09/20 => 2016/08/10 ~ 2016/09/15
range③  2016/09/15 ~ 2016/10/10 => x out of the scope
range④  2016/08/01 ~ 2016/09/30 => 2016/08/05 ~ 2016/09/15

2 个答案:

答案 0 :(得分:4)

您可以使用least()函数获取较低的值:

select  greatest(current_period_start_at, date '2016-08-05') as range_start, 
        least(current_period_end_at, date '2016-09-15') as range_end
from subscriptions
where (current_period_start_at,current_period_end_at) 
         overlaps (date '2016-08-05', date '2016-09-15');

如果您不想重复日期值,可以使用公用表表达式:

with range (r_start, r_end) as (
  values (date '2016-08-05', date '2016-09-15')
)
select greatest(current_period_start_at, r_start) as range_start,
       least(current_period_end_at, r_end) as range_end
from subscriptions, range
where (current_period_start_at,current_period_end_at) 
      overlaps (r_start, r_end);

答案 1 :(得分:3)

您应该尝试使用daterange数据类型。

SELECT daterange('2017-01-01'::date, '2017-03-01'::date) * daterange('2017-02-15'::date, '2017-05-01'::date);

返回

[2017-02-15,2017-03-01)