2017-09-26 50 views
1

我正在開展一個項目,在這個項目中,會計年度由三個月度來衡量,而且聽起來很奇怪,每個三個月都是從該月份的第10天開始計量,而不是按照國家/地區規定計算的第一天。因此,第一個三個月被認爲在1月10日開始,並在那個月的9號之後的三個月結束。有沒有辦法date_trunc或簡單地在PostgreSQL中使用這些自定義三個月的時間戳列?如何在PostgreSQL的自定義三學期date_trunc?

到目前爲止,我只能夠與像查詢按月/天/周的數據:

FROM myTable SELECT( SUM(price) as total, date_trunc('month', 'timpestamp') ) GROUP BY (total)

回答

1

使用函數(或它裏面的表情):

create or replace function get_trimester(timestamp) 
returns integer language sql immutable as $$ 
    select (extract('month' from $1::date- 9)::int- 1)/ 3 + 1 
$$; 

檢查功能對某些日期:

with my_table(t) as (
values 
    ('2017-01-09'::timestamp), 
    ('2017-01-10'), 
    ('2017-04-09'), 
    ('2017-04-10'), 
    ('2017-07-09'), 
    ('2017-07-10'), 
    ('2017-10-09'), 
    ('2017-10-10'), 
    ('2017-12-31') 
) 

select t, get_trimester(t) 
from my_table 

      t   | get_trimester 
---------------------+--------------- 
2017-01-09 00:00:00 |    4 
2017-01-10 00:00:00 |    1 
2017-04-09 00:00:00 |    1 
2017-04-10 00:00:00 |    2 
2017-07-09 00:00:00 |    2 
2017-07-10 00:00:00 |    3 
2017-10-09 00:00:00 |    3 
2017-10-10 00:00:00 |    4 
2017-12-31 00:00:00 |    4 
(9 rows) 
+0

我最終使用這種方法。對我來說生成日期序列更容易。謝謝! – Ivan

1

喲可以加入結果agants準備時間間隔,如:

t=# select starts,starts+'3 month'::interval ends,mod(ord,4) from generate_series('2015-10-01'::date,'2018-10-01'::date,'3 month'::interval) with ordinality t(starts,ord); 
     starts   |   ends   | mod 
------------------------+------------------------+----- 
2015-10-01 00:00:00+00 | 2016-01-01 00:00:00+00 | 1 
2016-01-01 00:00:00+00 | 2016-04-01 00:00:00+00 | 2 
2016-04-01 00:00:00+00 | 2016-07-01 00:00:00+00 | 3 
2016-07-01 00:00:00+00 | 2016-10-01 00:00:00+00 | 0 
2016-10-01 00:00:00+00 | 2017-01-01 00:00:00+00 | 1 
2017-01-01 00:00:00+00 | 2017-04-01 00:00:00+00 | 2 
2017-04-01 00:00:00+00 | 2017-07-01 00:00:00+00 | 3 
2017-07-01 00:00:00+00 | 2017-10-01 00:00:00+00 | 0 
2017-10-01 00:00:00+00 | 2018-01-01 00:00:00+00 | 1 
2018-01-01 00:00:00+00 | 2018-04-01 00:00:00+00 | 2 
2018-04-01 00:00:00+00 | 2018-07-01 00:00:00+00 | 3 
2018-07-01 00:00:00+00 | 2018-10-01 00:00:00+00 | 0 
2018-10-01 00:00:00+00 | 2019-01-01 00:00:00+00 | 1 
(13 rows) 

這裏你可以使用rownum命令的剩餘部分除以semestres數來獲得學期數(當然,你需要處理0--要麼稱它爲4,要麼從減一個學期開始,只使用mod(ord,4)+1,或者使用case when等)

+0

感謝你們給我很大的反響。我通過創建一個函數來解決這個問題,而不是像上面的klin的例子那樣。 – Ivan