1

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

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

这可能吗?

4

3 回答 3

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);
于 2013-07-04T13:24:15.670 回答
3
select *
from 
    (
        select generate_series(
            '2013-05-01'::date, '2013-05-05', '1 day'
            )::date
    ) s("date")
    left join
    t using ("date")

将两者都替换"date"为实际的列名。

于 2013-07-04T13:47:00.593 回答
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是一个可怕的列名称。除了它是一个保留字这一事实之外,它也没有说明它是什么类型的“日期”。

于 2013-07-04T13:24:01.067 回答