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.

SqlData Integrity

Code

snippet
-- 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: WHERE first, 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

FAQ

Which tables or CTEs does it reference?
`results` — referenced directly, no join needed.