我在PostgreSQL数据库中使用SELECT查询得到以下结果:player_id points time395 0 2018-06-01 17:55:23.982413-04395 100 2018-06-30 11:05:21.8679-04395 0 2018-07-15 21:56:25.420837-04395 100 2018-07-28 19:47:13.84652-04395 0 2018-11-27 17:09:59.384-05395 100 2018-12-02 08:56:06.83033-05399 0 2018-05-15 15:28:22.782945-04399 100 2018-06-10 12:11:18.041521-04454 0 2018-07-10 18:53:24.236363-04675 0 2018-08-07 20:59:15.510936-04696 0 2018-08-07 19:09:07.126876-04756 100 2018-08-15 08:21:11.300871-04756 100 2018-08-15 16:43:08.698862-04756 0 2018-08-15 17:22:49.755721-04756 100 2018-10-07 15:30:49.27374-04756 0 2018-10-07 15:35:00.975252-04756 0 2018-11-27 19:04:06.456982-05756 100 2018-12-02 19:24:20.880022-05756 100 2018-12-04 19:57:48.961111-05我试着找出每个球员最长的连胜记录在哪里,平局是最近开始的。我还需要确定该球员最长连胜开始的时间。预期结果将是:player_id longest_streak time_began395 1 2018-12-02 08:56:06.83033-05399 1 2018-06-10 12:11:18.041521-04756 2 2018-12-02 19:24:20.880022-05 最佳答案 确实是个问题。假设:“连胜”不会被其他玩家的排打断。所有列都定义为NOT NULL。(否则你必须做更多。)这应该是最简单和最快的,因为它只需要两次快速gaps-and-islands:SELECT DISTINCT ON (player_id) player_id, count(*) AS seq_len, min(ts) AS time_beganFROM ( SELECT player_id, points, ts , row_number() OVER (PARTITION BY player_id ORDER BY ts) - row_number() OVER (PARTITION BY player_id, points ORDER BY ts) AS grp FROM tbl ) subWHERE points = 100GROUP BY player_id, grp -- omit "points" after WHERE points = 100ORDER BY player_id, seq_len DESC, time_began DESC;分贝小提琴row_number() window functions使用列名ts而不是标准SQL中的here。在Postgres中是允许的,但是有一些限制,使用它作为标识符仍然是个坏主意。“诀窍”是减去行号,使每个行的连续行落在同一组(time)中。然后过滤那些100分的,每个组加起来,只返回最长的,每个玩家最近的结果。基本技术说明:reserved word我们可以在grp中使用(player_id, points)和GROUP BY,在DISTINCT ON之前应用SELECT。考虑GROUP BY查询中的事件序列:Select longest continuous sequence关于DISTINCT ON:Best way to get result count before LIMIT was applied关于sql - 找到每位玩家最长的完美成绩连胜纪录,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56583326/ 10-15 21:02