Rows Frame Without Current Row
Aggregate the strictly previous rows with ROWS BETWEEN n PRECEDING AND 1 PRECEDING: the current row never influences its own look-back statistic.
Code
-- 严格的“前 N 行”frame:3 PRECEDING AND 1 PRECEDING 把 current row 排除在外,
-- 当前值不会污染自己的 look-back 统计;帧为空时 AVG 为 NULL、COUNT 为 0
WITH trades (day, cents) AS (
VALUES (1, 100), (2, 200), (3, 300), (4, 400), (5, 500)
)
SELECT
day, cents,
AVG(cents) OVER (
ORDER BY day
ROWS BETWEEN 3 PRECEDING AND 1 PRECEDING
) AS prev3_avg,
COUNT(*) OVER (
ORDER BY day
ROWS BETWEEN 3 PRECEDING AND 1 PRECEDING
) AS prev3_count
FROM trades
ORDER BY day;
-- day 1:帧空 → NULL / 0;day 2 只有 day1;day 4 起才是完整三行(200)What the code does
What runs is SELECT, with trades as the object involved.
Mechanically, the statements are built from: a CTE (WITH … AS) that names an intermediate result before the main query; COUNT, AVG aggregation; a window function (OVER (…)) computing values across rows without collapsing them; an ORDER BY that fixes the output order.
Caveats
- Remember the evaluation order:
WHEREfirst, window functions later — filtering on the latter needs another query level.
Applying it
The trades 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
- What relations does the SQL touch?
- The references are `trades`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.