2017-03-02 54 views
3

我使用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 =>2017/03/01 current_period_end_at:2017/04/02 =>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 

回答

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); 
+0

感谢您的回答!但我希望过滤当前期间'2017-03-01',日期'2017-03-31'之间的记录,然后修正这些日期,如果它们超出范围。 – Tosh

+0

对不起,我的解释。如果目标范围是2016年8月5日〜2016年9月15日,并且A(2016年7月1日〜2016年8月31日在该范围内,但我希望截止日期超出范围在这种情况下,2016/07/01应该是2016/08/05。 – Tosh

+0

@Tosh:请参阅我的编辑 –

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) 
+0

我知道这将是可能的日期范围;) –