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 に答える
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 に答える