【发布时间】:2015-03-29 10:13:20
【问题描述】:
感谢Mike 提出添加创建/插入语句的建议。
create table test (
pid integer not null,
date date not null,
primary key (pid, date)
);
insert into test values
(1,'2014-10-1')
, (1,'2014-10-2')
, (1,'2014-10-3')
, (1,'2014-10-5')
, (1,'2014-10-7')
, (2,'2014-10-1')
, (2,'2014-10-2')
, (2,'2014-10-3')
, (2,'2014-10-5')
, (2,'2014-10-7');
我想添加一个新列,即“当前连续天数” 所以 结果 看起来像:
pid | date | in_streak
-------|-----------|----------
1 | 2014-10-1 | 1
1 | 2014-10-2 | 2
1 | 2014-10-3 | 3
1 | 2014-10-5 | 1
1 | 2014-10-7 | 1
2 | 2014-10-2 | 1
2 | 2014-10-3 | 2
2 | 2014-10-4 | 3
2 | 2014-10-6 | 1
我一直在尝试使用来自
的答案但我不知道如何将 dense_rank() 技巧与其他窗口函数一起使用以获得正确的结果。
【问题讨论】:
-
您说过,“pid 是唯一的,而 date 不是。”但是您的数据表明日期是唯一的,而 pid 不是。哪个是对的?
-
日期不是唯一的,因为多个 pid 可以具有相同的日期。我会让问题更清楚。
标签: sql postgresql window-functions date-arithmetic gaps-and-islands