
We present a SQL-based customer segmentation framework that computes Recency, Frequency, and Monetary metrics over a rolling three-year window and tracks segment transitions between consecutive years. Using window functions including NTILE for quantile-based ranking and LAG for year-over-year segment comparison, the system classifies customers into five loyalty tiers: VIP, Regular, Loyal, Potential, and Lost. The methodology is implemented in standard SQL with support for PostgreSQL, Oracle, and other databases supporting EXTRACT and window functions. The query handles over 10 million order records with linear scaling, producing actionable business intelligence on customer churn prediction and loyalty dynamics. Segment definitions are configurable through quantile thresholds, allowing adaptation to different business domains.
