我正在研究 postgres 9.3.2,我有这个表:
id startdate enddate no_of_days_between
1 2010-12-22 2010-12-23 1
1 2010-12-23 2010-12-24 1
1 2010-12-24 2010-12-25 1
1 2010-12-25 2010-12-26 1
1 2010-12-26 2010-12-27 1
1 2010-12-27 2010-12-28 1
1 2010-12-28 2010-12-29 1
1 2010-12-29 2011-03-06 67
1 2011-03-06 2011-03-07 1
1 2011-03-07 2011-03-08 1
1 2011-03-08 2011-03-09 1
我想要做的是找到连续几天的记录。为此,我在此查询中使用 row_number 窗口函数:
select t.*, row_number() over (partition by no_of_days_between order by enddate) as no_of_consecutive_days from t
我想要返回的是这样的:
id startdate enddate no_of_days no_of_consecutive_days
_between
1 2010-12-22 2010-12-23 1 1
1 2010-12-23 2010-12-24 1 2
1 2010-12-24 2010-12-25 1 3
1 2010-12-25 2010-12-26 1 4
1 2010-12-26 2010-12-27 1 5
1 2010-12-27 2010-12-28 1 6
1 2010-12-28 2010-12-29 1 7
1 2010-12-29 2011-03-06 67 1
1 2011-03-06 2011-03-07 1 1
1 2011-03-07 2011-03-08 1 2
1 2011-03-08 2011-03-09 1 3
但是查询返回的内容更像是先按 no_of_days_ Between 排序,然后按 enddate 排序,所以我返回:
id startdate enddate no_of_days no_of_consecutive_days
_between
1 2010-12-22 2010-12-23 1 1
1 2010-12-23 2010-12-24 1 2
1 2010-12-24 2010-12-25 1 3
1 2010-12-25 2010-12-26 1 4
1 2010-12-26 2010-12-27 1 5
1 2010-12-27 2010-12-28 1 6
1 2010-12-28 2010-12-29 1 7
1 2011-03-06 2011-03-07 1 8
1 2011-03-07 2011-03-08 1 9
1 2011-03-08 2011-03-09 1 10
1 2010-12-29 2011-03-06 67 1
有人遇到过这个问题吗?如何强制它先排序再分区?
谢谢
最佳答案
您仍然需要在查询末尾添加“ORDER BY enddate”,否则行的顺序就是 postgres 想要给您的任何顺序。
OVER 子句中的 ORDER BY 仅控制 row_number() 如何查看数据,而不控制数据最终如何返回。
关于Postgresql row_number 不按日期排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21411845/