Nth Value Second Highest In Frame

Pick the second row of a window frame with nth_value; the default frame gives a moving answer while an unbounded full frame pins one constant runner-up.

SqlData Fetching

Code

snippet
-- nth_value(value, n):返回窗口帧内第 n 行的值——"第二名/第三名"的直接来源。
-- 默认帧是 RANGE UNBOUNDED PRECEDING TO CURRENT ROW,只到当前行为止,
-- 所以第一行的第 2 名是 NULL;展开成全帧后,每组第 2 名固定下来。
WITH scores AS (
  SELECT * FROM (VALUES
    ('ada',   98),
    ('linus', 91),
    ('alan',  87),
    ('kay',   85)
  ) AS t(player, points)
)
SELECT
  player,
  points,
  NTH_VALUE(player, 2) OVER w AS second_so_far,
  NTH_VALUE(player, 2) OVER (
      ORDER BY points DESC
      ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS second_overall,
  FIRST_VALUE(player) OVER (
      ORDER BY points DESC
      ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS champion
FROM scores
WINDOW w AS (ORDER BY points DESC)
ORDER BY points DESC;

How it works

The WITH scores AS (...) CTE turns four VALUES rows — ('ada', 98), ('linus', 91), ('alan', 87), ('kay', 85) — into a queryable relation aliased t(player, points). The select list then reads one column three ways through window functions: NTH_VALUE(player, 2) OVER w AS second_so_far reuses the named window WINDOW w AS (ORDER BY points DESC), whose default frame is RANGE UNBOUNDED PRECEDING TO CURRENT ROW — the file’s comment spells out that this frame only reaches the current row, so the first row’s second value is still NULL and the answer moves as rows advance. The other two calls write the frame out instead: ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING exposes the whole partition, so second_overall returns the same runner-up (linus) on every row and FIRST_VALUE(player) ... AS champion pins ada. ORDER BY points DESC lines the comparison up row by row.

What to watch for

  • Same function, different frame, different answer: the two NTH_VALUE(player, 2) calls differ only in the frame clause — the named window w keeps the moving default, the explicit full frame returns a constant.
  • The file’s comment names the default frame (RANGE UNBOUNDED PRECEDING TO CURRENT ROW) as the reason the first row has no second value yet.

Key statements

WINDOW w AS (ORDER BY points DESC)
NTH_VALUE(player, 2) OVER w AS second_so_far,

Interactive Tools for This Topic

FAQ

Why is second_so_far NULL on the first row?
`OVER w` uses the default frame `RANGE UNBOUNDED PRECEDING TO CURRENT ROW`; on the first row that frame holds a single row, so `NTH_VALUE(player, 2)` has no second value to return yet — the file's comment states exactly this.
What makes second_overall constant across rows?
Its frame is spelled out as `ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING`, so every row sees the whole partition and `NTH_VALUE(player, 2)` always resolves to the same runner-up (`linus`).