Loading lesson...
Look back. Look forward. Frame it.
Look back. Look forward. Frame it.
Topics covered: LAG and LEAD, FIRST, LAST, NTH VALUE, Frame Specifications, NTILE and Bucketing, Multiple Windows
LAG and LEAD Fundamentals Understanding the syntax and behavior of these functions is essential before applying them to real analytics scenarios. The Syntax Why Not a Self-Join? Before window functions existed, comparing a row to its predecessor required joining a table to itself. You would match each row to the previous row by offsetting a date or sequence column. This works, but it has real costs. Month-Over-Month Comparison Practical Applications LEAD for Change Detection Detecting Sequential
Positional Function Basics Each positional function accesses a specific row within the window frame. Understanding their syntax and default behaviors is essential for correct usage. FIRST_VALUE Every employee can see how far their salary is from the highest in their department. The person with the top salary has a gap of zero. This pattern is commonly used in compensation analysis to show each employee their relative position without revealing other individuals' exact salaries. The LAST_VALUE Fr
Frame specifications define exactly which rows participate in a window calculation. Every window function operates on a frame, and understanding frames is the key to unlocking the full power of window functions. Up to this point, you have been relying on the default frame, which extends from the beginning of the partition to the current row. That default works for running totals but fails for many other patterns. To build moving averages, trailing windows, and centered calculations, you need to
NTILE Fundamentals Basic NTILE Usage Consider a customer segmentation scenario. A marketing team wants to divide customers into four spending tiers to target campaigns differently. The top quartile gets exclusive offers, the bottom quartile gets re-engagement campaigns. With 8 rows divided into 4 groups, each group gets exactly 2 rows. Quartile 1 contains the highest spenders and quartile 4 the lowest. This is a clean division because 8 divides evenly by 4. Handling Remainders The rule is simple
Real-world analysis often requires comparing a row from multiple perspectives in the same query. You might need a rank within a department, a running total across the company, and a comparison to the previous month all in one result set. Multiple Window Definitions Each window function in a query can have its own partitioning, ordering, and framing. This flexibility lets you answer multiple questions in a single pass over the data. Different Partitions Here is a practical example: for each sale,