使用函數(或它裏面的表情):
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)
我最終使用這種方法。對我來說生成日期序列更容易。謝謝! – Ivan