2017-03-02 48 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

我知道這將是可能的日期範圍;) –