我的postgres数据库中有一个表'广告',其中包含“开始”和“结束”列,如:
ID Start End
1 2003-06-07 00:00:00 2004-09-30 23:59:59
我怎样才能将这个持续时间(从2003年到2004年)分成两部分,以便开始和结束日期(时间戳)应该保持在同一年这样?
ID Start End
1_2003 2003-06-07 00:00:00 2003-12-31 23:59:59
1_2004 2004-01-01 00:00:00 2004-09-30 23:59:59
我想知道窗口功能是否有助于实现这一目标?我正在使用PostgreSQL版本9.5(x64)。
答案 0 :(得分:1)
示例数据:
create table ad (id text, start_t timestamp, end_t timestamp);
insert into ad values
(1, '2003-06-07 00:00:00', '2004-09-30 23:59:59'),
(2, '2002-02-02 00:00:00', '2004-04-04 23:59:59');
查询:
select
concat(id, '_', y) id,
case
when extract(year from start_t)::int = y then start_t
else make_timestamp(y, 1, 1, 0, 0, 0) end as "start",
case
when extract(year from end_t)::int = y then end_t
else make_timestamp(y, 12, 31, 23, 59, 59) end as "end"
from
ad,
generate_series(extract(year from start_t)::int, extract(year from end_t)::int) y;
id | start | end
--------+---------------------+---------------------
1_2003 | 2003-06-07 00:00:00 | 2003-12-31 23:59:59
1_2004 | 2004-01-01 00:00:00 | 2004-09-30 23:59:59
2_2002 | 2002-02-02 00:00:00 | 2002-12-31 23:59:59
2_2003 | 2003-01-01 00:00:00 | 2003-12-31 23:59:59
2_2004 | 2004-01-01 00:00:00 | 2004-04-04 23:59:59
(5 rows)