PostgreSQL增量日期?

时间:2013-07-04 13:20:24

标签: sql postgresql generate-series

我有一个包含以下数据的数据库表:

ID | Date       | Bla
1  | 2013-05-01 | 1
2  | 2013-05-02 | 2
3  | 2013-05-03 | 3
4  | 2013-05-05 | 4

请注意,缺少日期:2014-05-04。我该如何更改以下查询:

SELECT * 
FROM table 
where DATE >= '2013-05-01' AND DATE <= '2013-05-05'

这样我最终得到以下输出:

ID   | Date       | Bla
1    | 2013-05-01 | 1
2    | 2013-05-02 | 2
3    | 2013-05-03 | 3
null | 2013-05-04 | null
4    | 2013-05-05 | 4

这可能吗?

3 个答案:

答案 0 :(得分:3)

您可以加入generate_series输出:

select
    '2013-05-01'::date + g.o AS "date with offset"
from
    generate_series(0, 30) AS g(o)

输出:

"2013-05-01"
"2013-05-02"
"2013-05-03"
...
"2013-05-29"
"2013-05-30"
"2013-05-31"

或者......定义新的存储过程后更简单的方法:)

CREATE OR REPLACE FUNCTION generate_series(date, date) RETURNS
SETOF date AS $$
SELECT $1 + g.s
FROM generate_series(0, ($2 - $1)) AS g(s);
$$ LANGUAGE SQL IMMUTABLE;

就这样称呼它:

SELECT * FROM generate_series(start_date, end_date);

答案 1 :(得分:3)

select *
from 
    (
        select generate_series(
            '2013-05-01'::date, '2013-05-05', '1 day'
            )::date
    ) s("date")
    left join
    t using ("date")

"date"替换为实际的列名。

答案 2 :(得分:2)

您需要将表格外部加入“日期列表”:

with all_dates (some_date) as (
    select date '2013-05-01' + i 
    from generate_series(0, 10) i  -- adjust here to the range of dates you need.
) 
select t.id, 
       ad.some_date, -- you need to take the actual date from generated ones
       t.bla
from all_dates ad
  left join the_table t on ad.some_date = t.date
where ad.some_date between date '2013-05-01' and date '2013-05-05';

顺便说一下:date是一个可怕的名字。除了它是一个保留字之外,它也没有说明什么样的“日期”。