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.

SqlData Fetching

Code

snippet
-- 严格的“前 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: WHERE first, 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

FAQ

What relations does the SQL touch?
The references are `trades`.