[英]Consecutive dates postgresql
I need to know if there are no consecutive dates per document. 我需要知道每个文档是否没有连续的日期。 I have this table:
我有这张桌子:
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
AS you can see there is only one gap: In document 2 the '2015-01-02' is missing. 正如您所看到的,只有一个差距:在文档2中,缺少“ 2015-01-02”。 I want to know this gap.
我想知道这个差距。 I have this select:
我有这个选择:
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)
This select is giving me a register per date, and the gap, that in most of cases is 1, but when another document is starting in the result, it gives me the gap wrong. 这个选择给我每个日期一个寄存器,并且该间隙在大多数情况下是1,但是当另一个文件开始显示结果时,它给我间隙是错误的。 I dont know if this is the correct way or to make a function... Here the code to build the table:
我不知道这是正确的方法还是要创建一个函数...下面是构建表的代码:
--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');
If you don't specify a PARTITION
PostgreSQL will assume it is the whole table. 如果您未指定
PARTITION
PostgreSQL将假定它是整个表。 Your query should include the PARTITION BY
clause: 您的查询应包括
PARTITION BY
子句:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.