尝试找出填充此表中最后一列的最快方法,streak
列存储结果值的运行(win
或loss
)。
game_date | team | result | streak
------------+---------+--------+--------
2017-10-05 | ABC | win | 1
2017-10-07 | ABC | win | 2
2017-10-11 | ABC | loss | 1
2017-10-14 | ABC | win | 1
2017-10-15 | ABC | win | 2
2017-10-18 | ABC | win | 3
2017-10-21 | ABC | win | 4
2017-10-23 | ABC | loss | 1
2017-10-24 | ABC | win | 1
2017-10-26 | ABC | win | 2
2017-10-28 | ABC | win | 3
2017-10-30 | ABC | loss | 1
2017-11-02 | ABC | win | 1
2017-11-04 | ABC | loss | 1
2017-11-07 | ABC | win | 1
2017-11-09 | ABC | loss | 1
2017-11-12 | ABC | loss | 1
2017-11-14 | ABC | loss | 2
2017-11-16 | ABC | loss | 3
2017-11-18 | ABC | win | 1
2017-11-19 | ABC | loss | 1
2017-11-22 | ABC | loss | 2
2017-11-24 | ABC | loss | 3
2017-11-25 | ABC | win | 1
2017-11-28 | ABC | win | 2
2017-11-30 | ABC | win | 3
2017-12-01 | ABC | win | 4
(27 rows)
如您所见,streak
应该在前一个结果为空或不同时重置为1,否则递增一个。
答案 0 :(得分:0)
您可以使用row_numbers()
的差异来识别结果值的“孤岛”,从而确定胜负的顺序。其余的只是最终申请row_number()
:
select g.*,
row_number() over (partition by seqnum - seqnum_r, result order by game_date) as streak
from (select g.*,
row_number() over (order by game_date) as seqnum,
row_number() over (partition by result order by game_date) as seqnum_r
from games g
) g