Named Window Clause Reuse

Name a window once in a WINDOW clause and reuse it with OVER w, appending frame clauses without repeating partition and order definitions.

SqlData Fetching

Code

snippet
-- WINDOW 子句给分区与排序命名:多个窗口函数复用同一窗口,改一处全局生效
-- 引用命名窗口时只能追加帧子句,不能再写 PARTITION BY / ORDER BY
SELECT
  endpoint,
  occurred_at,
  latency_ms,
  ROW_NUMBER() OVER w AS seq,
  LAG(latency_ms) OVER w AS prev_latency,
  latency_ms - LAG(latency_ms) OVER w AS delta_ms,
  AVG(latency_ms) OVER (w ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS rolling_avg,
  -- 同一查询可以定义多个命名窗口
  RANK() OVER w2 AS latency_rank
FROM request_log
WINDOW w AS (PARTITION BY endpoint ORDER BY occurred_at),
       w2 AS (PARTITION BY endpoint ORDER BY latency_ms DESC)
ORDER BY endpoint, occurred_at;

How it works

The statement is SELECT, touching request_log.

The pieces that do the work: AVG aggregation; a window function (OVER (…)) computing values across rows without collapsing them; an ORDER BY that fixes the output order.

What to watch for

  • Window functions evaluate after WHERE/GROUP BY, so filtering on their output in the same-level WHERE will not work — use an outer query or a CTE.

Putting it to use

The request_log table is the working surface here.

Interactive Tools for This Topic

FAQ

Which objects does the SQL touch?
`request_log` — referenced directly, no join needed.