在PostgreSQL中显示带有NULL的完整日期范围

时间:2019-06-13 10:27:28

标签: postgresql postgresql-9.4

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

例如,这是我的 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')

如何输出范围中所有可能为null的日期

预期输出:

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

2 个答案:

答案 0 :(得分:1)

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

结果


答案 1 :(得分:1)

好的,请看下面的我的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