小编Kip*_*Kip的帖子

Postgres窗口(确定连续的天数)

使用Postgres 9.3,我试图计算某种天气类型的连续天数.如果我们假设我们有定期的时间序列和天气预报:

date|weather
"2016-02-01";"Sunny"
"2016-02-02";"Cloudy"
"2016-02-03";"Snow"
"2016-02-04";"Snow"
"2016-02-05";"Cloudy"
"2016-02-06";"Sunny"
"2016-02-07";"Sunny"
"2016-02-08";"Sunny"
"2016-02-09";"Snow"
"2016-02-10";"Snow"
Run Code Online (Sandbox Code Playgroud)

我想要的东西算在同一天气的连续日子里.结果应如下所示:

date|weather|contiguous_days 
"2016-02-01";"Sunny";1
"2016-02-02";"Cloudy";1
"2016-02-03";"Snow";1
"2016-02-04";"Snow";2
"2016-02-05";"Cloudy";1
"2016-02-06";"Sunny";1
"2016-02-07";"Sunny";2
"2016-02-08";"Sunny";3
"2016-02-09";"Snow";1
"2016-02-10";"Snow";2
Run Code Online (Sandbox Code Playgroud)

我一直在尝试使用窗口函数.起初,它似乎应该是明智的,但后来我发现它比预期的要困难得多.

这是我试过的......

Select date, weather, Row_Number() Over (partition by weather order by date)
  from t_weather
Run Code Online (Sandbox Code Playgroud)

将当前行与下一行进行比较会更容易吗?在保持计数的同时,你会怎么做?任何想法,想法,甚至解决方案都会有所帮助!-Kip

sql postgresql window-functions gaps-and-islands

7
推荐指数
1
解决办法
561
查看次数