GROUPS Frame Mode Counts Peer Rows
Include tied rows as one unit with the GROUPS frame mode, so the peer count moves group by group instead of row by row like ROWS.
Code
-- GROUPS 帧模式:把相邻的 peer rows(同分并列行)当作整体进出窗口
-- 对比 ROWS 模式逐行滑动:GROUPS mode 下并列行一起进、一起出
WITH results AS (
SELECT * FROM (VALUES
('ada', 'A', 92),
('ben', 'A', 92),
('cy', 'A', 88),
('dee', 'B', 76),
('eli', 'B', 71)
) AS t(name, grade, score)
)
SELECT
name,
grade,
score,
COUNT(*) OVER (
PARTITION BY grade
ORDER BY score
GROUPS BETWEEN 1 PRECEDING AND CURRENT ROW
) AS peers_in_frame,
COUNT(*) OVER (
PARTITION BY grade
ORDER BY score
ROWS BETWEEN 1 PRECEDING AND CURRENT ROW
) AS rows_in_frame
FROM results
ORDER BY grade, score, name;How it works
At its core this is a single SELECT statement against results.
In terms of clauses, the statements use: a CTE (WITH … AS) that names an intermediate result before the main query; COUNT aggregation; a window function (OVER (…)) computing values across rows without collapsing them; an ORDER BY that fixes the output order.
What to watch for
- Remember the evaluation order:
WHEREfirst, window functions later — filtering on the latter needs another query level.
Putting it to use
The results table is the working surface here.
Interactive Tools for This Topic
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Which tables or CTEs does it reference?
- `results` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.