PARTITION BY: Grouping Inside Your Window
Welcome to **Day 63**. Today we combine the power of grouping with the flexibility of windows using `PARTITION BY`.
What is a Partition?
A partition tells the window function: "Reset your calculation every time this column changes."
Real-World Example: Top Product inside each Category
If you want to find the top-selling product in *each* category (Electronics, Clothing, Food), a global rank won't work.
SELECT
category,
product_name,
sales,
RANK() OVER(PARTITION BY category ORDER BY sales DESC) as rank_in_category
FROM products;
How it works
The database "buckets" the rows by category, sorts them by sales within that category, and assigns ranks. Then it starts over for the next category.
Why analysts love it
It allows you to answer complex questions like "Who is the highest paid person in every department?" or "What was the latest order for every customer?" in a single query.
Your Task for Today
Rank your employees by salary, but partitioned by their department.
*Day 64: LAG & LEAD—Looking into the Past and Future.*