在 PostgreSQL 中使用 NULL 显示完整的日期范围

Show complete date range with NULL in PostgreSQL

如果 table

上不存在日期,我正在尝试创建此查询以获取范围内的所有完整日期和带空值的数据

例如这是我的 tbl_example

原始数据:

id | userid(str) | comment(str) | mydate(date)
1     0001          sample1      2019-06-20T16:00:00.000Z
2     0002          sample2      2019-06-21T16:00:00.000Z
3     0003          sample3      2019-06-24T16:00:00.000Z
4     0004          sample4      2019-06-25T16:00:00.000Z
5     0005          sample5      2019-06-26T16:00:00.000Z

然后:

select * from tbl_example where mydate between '2019-06-20' AND
DATE('2019-06-20') + interval '5 day')

如何像这样输出可能为空的范围内的所有日期

预期输出:

id | userid(str) | comment(str) | mydate(date)
1     0001          sample1      2019-06-20T16:00:00.000Z
2     0002          sample2      2019-06-21T16:00:00.000Z
null  null          null         2019-06-22T16:00:00.000Z
null  null          null         2019-06-23T16:00:00.000Z
4     0003          sample3      2019-06-24T16:00:00.000Z
5     0004          sample4      2019-06-25T16:00:00.000Z 

这是我的示例测试环境:http://www.sqlfiddle.com/#!17/f5285/2

SELECT id, userid, "comment", d.mydate
    FROM generate_series('2019-06-20'::date, '2019-06-25'::date, INTERVAL '1 day') d (mydate)
    LEFT JOIN tbl_example ON d.mydate = tbl_example.mydate

结果


好的,看看我的SQL如下:

with all_dates as (
select generate_series(min(mydate),max(mydate),'1 day'::interval) as dates from tbl_example
)
,null_dates as (
select
    a.dates
from
    all_dates a
left join
    tbl_example t on a.dates = t.mydate
where
    t.mydate is null
)
select null as id, null as userid, null as comment, dates as mydate from null_dates
union
select * from tbl_example order by mydate;
 id | userid | comment |       mydate        
----+--------+---------+---------------------
  1 | 0001   | sample1 | 2019-06-20 16:00:00
  2 | 0002   | sample1 | 2019-06-21 16:00:00
    |        |         | 2019-06-22 16:00:00
    |        |         | 2019-06-23 16:00:00
  3 | 0003   | sample1 | 2019-06-24 16:00:00
  4 | 0004   | sample1 | 2019-06-25 16:00:00
  5 | 0005   | sample1 | 2019-06-26 16:00:00
(7 rows)

或者generate_series子句你可以只写你想要的日期参数,如下:

select generate_series('2019-06-20 16:00:00','2019-06-20 16:00:00'::timestamp + '5 days'::interval,'1 day'::interval) as dates