连续日期postgresql
我需要知道每个文档是否没有连续的日期。我有这张桌子:连续日期postgresql,sql,postgresql,gaps-and-islands,Sql,Postgresql,Gaps And Islands,我需要知道每个文档是否没有连续的日期。我有这张桌子: document | the_day 1 | 2015-01-01 1 | 2015-01-02 1 | 2015-01-03 1 | 2015-01-04 1 | 2015-01-05 1 | 2015-01-06 2 | 2015-01-01 2 | 2015-01-03 2 |
document | the_day
1 | 2015-01-01
1 | 2015-01-02
1 | 2015-01-03
1 | 2015-01-04
1 | 2015-01-05
1 | 2015-01-06
2 | 2015-01-01
2 | 2015-01-03
2 | 2015-01-04
2 | 2015-01-05
2 | 2015-01-06
3 | 2015-01-01
3 | 2015-01-02
3 | 2015-01-03
3 | 2015-01-04
3 | 2015-01-05
3 | 2015-01-06
正如您所见,只有一个差距:文件2中缺少“2015-01-02”。
我想知道这个差距。
我有以下选择:
SELECT document, the_day, the_day - lag(the_day) OVER w AS gap
FROM mytable
where active=true and fault=false
WINDOW w AS (ORDER BY document,the_day)
这个选择给了我一个每个日期的寄存器,间隔,在大多数情况下是1,但是当另一个文档在结果中开始时,它给了我错误的间隔。
我不知道这是不是正确的方法,或者做一个函数。。。
下面是构建表的代码:
--Table: public.test_consecutives
--DROP TABLE public.test_consecutives;
CREATE TABLE public.test_consecutives (
document integer,
the_day date
) WITH (
OIDS = FALSE
);
ALTER TABLE public.test_consecutives
OWNER TO postgres;
INSERT INTO test_consecutives (document, the_day) VALUES
(1, '2015-01-01'),
(1, '2015-01-02'),
(1, '2015-01-03'),
(1, '2015-01-04'),
(1, '2015-01-05'),
(1, '2015-01-06'),
(2, '2015-01-01'),
(2, '2015-01-03'),
(2, '2015-01-04'),
(2, '2015-01-05'),
(2, '2015-01-06'),
(3, '2015-01-01'),
(3, '2015-01-02'),
(3, '2015-01-03'),
(3, '2015-01-04'),
(3, '2015-01-05'),
(3, '2015-01-06');
如果不指定
分区
PostgreSQL将假定它是整个表。您的查询应包括分区依据
子句:
SELECT document, the_day, the_day - lag(the_day) OVER w AS gap
FROM mytable
where active=true and fault=false
WINDOW w AS (PARTITION BY document ORDER BY document,the_day)
如果不指定
分区
PostgreSQL将假定它是整个表。您的查询应包括分区依据
子句:
SELECT document, the_day, the_day - lag(the_day) OVER w AS gap
FROM mytable
where active=true and fault=false
WINDOW w AS (PARTITION BY document ORDER BY document,the_day)
如果不指定
分区
PostgreSQL将假定它是整个表。您的查询应包括分区依据
子句:
SELECT document, the_day, the_day - lag(the_day) OVER w AS gap
FROM mytable
where active=true and fault=false
WINDOW w AS (PARTITION BY document ORDER BY document,the_day)
如果不指定
分区
PostgreSQL将假定它是整个表。您的查询应包括分区依据
子句:
SELECT document, the_day, the_day - lag(the_day) OVER w AS gap
FROM mytable
where active=true and fault=false
WINDOW w AS (PARTITION BY document ORDER BY document,the_day)