我正在使用 PostgreSQL 12.0 并尝试获取特定列和值的最长连续行序列。
该表称为 team2,包含团队的结果,如下所示:
match_id (pk), team_name (varchar), opposition (varchar), match_result (varchar)
我的查询试图找到 match_result 中最长的“Win”序列。总共有 23 场胜利,用肉眼观察,最长的序列应该返回 5。然而,返回的是 23。如何更改查询以仅选择最长的序列?
WITH ConsecutiveSequences AS (
SELECT
match_result,
ROW_NUMBER() OVER () - ROW_NUMBER() OVER (ORDER BY match_id) AS grp
FROM team2
WHERE match_result = 'Win'
),
GroupedSequences AS (
SELECT
match_result,
COUNT(*) AS consecutive_count
FROM ConsecutiveSequences
GROUP BY match_result, grp
)
SELECT
COALESCE(MAX(consecutive_count), 0) AS longest_consecutive_sequence
FROM GroupedSequences;