sql – Postgres中的Generate_series,从表中的开始和结束日期开始

我一直在尝试从时间戳字段中的第一个日期到最后一个日期生成一系列日期(YYYY-MM-DD HH).我有我需要的generate_series(),但在尝试从表中获取开始和结束日期时遇到问题.我有以下几点给出一个粗略的想法:
with date1 as
(
SELECT start_timestamp as first_date
FROM header_table
ORDER BY start_timestamp DESC
LIMIT 1
),date2 as
(
SELECT start_timestamp as first_date
FROM header_table
ORDER BY start_timestamp ASC    
LIMIT 1
)
    select generate_series(date1.first_date,date2.first_date,'1 hour'::interval)::timestamp as date_hour

from
(   select * from date1
    union
    select * from date2) as foo

Postgres 9.3

解决方法

你当然不需要CTE.那将比必要的更昂贵.
并且您不需要转换为时间戳,因为当您将日期类型提供给 generate_series()时,结果已经是数据类型时间戳.

在Postgres 9.3或更高版本中,使用LAteraL连接最优雅地解决了这个问题:

SELECT to_char(ts,'YYYY-MM-DD HH24') AS formatted_ts
FROM  (
   SELECT min(start_timestamp) as first_date,max(start_timestamp) as last_date
   FROM   header_table
   ) h,generate_series(h.first_date,h.last_date,interval '1 hour') g(ts);

(可选)使用to_char()以您提到的格式将结果作为文本获取.
在早期(或任何)版本中:

SELECT generate_series(min(start_timestamp),max(start_timestamp),interval '1 hour') AS ts
FROM   header_table;

但是在SELECT列表中调用set-returns函数一个非标准的功能,并且有些人不赞成.如果可以,请使用第一个查询.

注意NULL处理的细微差别:

相当于

max(start_timestamp)

得到了

ORDER BY start_timestamp DESC NULLS LAST
LIMIT 1

如果没有NULLS,则LAST NULL值首先按降序排列(如果start_timestamp中可以有NULL值).对于last_date,您将获得NULL,并且您的查询将变为空.

细节:

> Why do NULL values come first when ordering DESC in a PostgreSQL query?

相关文章

SELECT a.*,b.dp_name,c.pa_name,fm_name=(CASE WHEN a.fm_n...
if not exists(select name from syscolumns where name=&am...
select a.*,pano=a.pa_no,b.pa_name,f.dp_name,e.fw_state_n...
要在 SQL Server 2019 中设置定时自动重启,可以使用 Window...
您收到的错误消息表明数据库 'EastRiver' 的...
首先我需要查询出需要使用SQL Server Profiler跟踪的数据库标...