FIRST_VALUE / LAST_VALUE : le piège du cadre par défaut
LAST_VALUE renvoie la ligne courante si on ne change pas le cadre par défaut (jusqu'à CURRENT ROW). Le correctif : étendre le cadre à UNBOUNDED FOLLOWING.
Cas d'usage
Récupérer le premier et le dernier état d'un abonnement sur chaque ligne d'historique.
Prérequis
PostgreSQL, SQL Server, MySQL 8+, Oracle
SQL
SELECT
user_id,
plan,
changed_at,
FIRST_VALUE(plan) OVER w AS first_plan,
-- Piège : sans cadre explicite, LAST_VALUE = ligne courante
LAST_VALUE(plan) OVER (
PARTITION BY user_id ORDER BY changed_at
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
) AS current_plan
FROM subscription_history
WINDOW w AS (PARTITION BY user_id ORDER BY changed_at);Résultat
user_id | plan | changed_at | first_plan | current_plan
---------+----------+------------+------------+--------------
42 | free | 2025-11-02 | free | business
42 | pro | 2026-01-15 | free | business
42 | business | 2026-04-20 | free | business
57 | pro | 2026-02-01 | pro | free
57 | free | 2026-05-12 | pro | free
(5 rows)SQLFIRST_VALUELAST_VALUEWindow frame