// window reference

SQL GROUPS frame

GROUPS counts groups of peers: 3 PRECEDING means the three preceding tie-groups, so tied rows always enter and leave frames together.

Categoria
Janela
Returns
per-frame aggregate
In this category
59 of 79

Sintaxe

SUM(x) OVER (ORDER BY d GROUPS BETWEEN 2 PRECEDING AND CURRENT ROW)

Suporte a mecanismos

MotorSupportNotas
SQL Server Not built in no GROUPS frame type, including SQL Server 2025
PostgreSQL Sim PostgreSQL 11+
MySQL Not built in rejected: 'This version of MySQL doesn't yet support GROUPS'
SQLite Sim SQLite 3.28+
Oracle Sim Oracle 21c+

Exemplos

PostgreSQL

-- average over the current peer group and the two before it
SELECT day, price,
       AVG(price) OVER (ORDER BY day GROUPS BETWEEN 2 PRECEDING AND CURRENT ROW) AS ma3_groups
FROM prices;

Bom saber

  • GROUPS differs from ROWS exactly on ties: with duplicate keys, ROWS can cut a tie group in half, GROUPS never does. With unique ORDER BY keys they are identical.
  • GROUPS differs from RANGE with numeric offsets by counting groups, not measuring value distance: RANGE 10 PRECEDING is a value band, GROUPS 10 PRECEDING is ten peer-groups back whatever their values.
  • SQL Server and MySQL reject GROUPS. When there are no ties GROUPS equals ROWS; with ties, aggregate to one row per ORDER BY value first, then use ROWS over those rows.

Questions about GROUPS Frame

When would I pick GROUPS over ROWS or RANGE?

When frames must align with distinct values: 'the last three distinct prices' regardless of how many rows each price has. ROWS cannot express it without splitting ties; RANGE cannot count groups.

Which engines lack GROUPS?

SQL Server and MySQL 8. Oracle added it in 21c, so Oracle 19c lacks it too. The rewrite is to collapse each tie group to one row (GROUP BY the ORDER BY value), run a ROWS frame over that, and join back.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

Cheat sheets for the engines that have it: PostgreSQL, SQLite, Oracle.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.