|
Hello Reader, Imagine this scenario: Your CMO walks into Monday's meeting with a question: "I need to see our top 3 highest-revenue expeditions in EACH category - hiking, climbing, safari, cultural, and photography." Most analysts would write 5 separate queries, one per category. Or export to Excel and manually filter. An hour of work, minimum. Confident analysts write one query using window functions. Takes 3 minutes. Here's the skill that separates intermediate analysts from advanced ones. Finding the "Top 3" Within Different Groups in Your DatasetYou want rankings WITHIN groups, not across the entire dataset. Not "the top 3 expeditions overall." But "the top 3 hiking trips, top 3 climbing trips, top 3 safari trips," etc. This is the "best within category" question that comes up constantly in business:
GROUP BY can't do this. You need window functions. SQL Window Functions Are The AnswerI ran this against the Summit Adventures database (the fake adventure tourism company I created to help people learn business analytics):
Here's what we found for Summit Adventures: Hiking (Top 3):
Climbing (Top 3):
Cultural (Top 3):
Safari (Top 3):
Photography (Top 3):
Translating this for the CMO at Summit AdventuresPhotography's top performer (Light & Landscape Course) generates the most revenue of any single expedition ($101K from 24 bookings). Cultural expeditions dominate with beginner-friendly trips, while hiking's top performer (Mountain Vista Trek) has the highest booking volume (19 bookings) in the hiking category. This tells marketing exactly where to focus promotion dollars within each category. For example: invest heavily in the Light & Landscape photography course (proven revenue leader), expand beginner cultural offerings (Heritage Discovery Walk generates $83K), and promote the Mountain Vista Trek for volume-based campaigns. Breaking Down The Window FunctionLines 18-22: The Window Function Magic
Let's break each piece down:
Think of PARTITION BY like creating invisible groups. Each group gets its own independent ranking starting from 1. Without window functions, you'd have to:
5 queries, 5 copy-paste operations, high chance of mistakes. With window functions: One query. All categories. All rankings. Done. Make Your Code Easier To Understand with CTEsNotice we used CTEs (Common Table Expressions) with the WITH keyword:
This breaks complex logic into readable steps:
You could write this as one massive nested query, but nobody would understand it. CTEs make your query tell a story and improve readability. Window Functions vs GROUP BYGROUP BY - Collapses rows into summary groups
Window Functions - Add calculations WITHOUT collapsing rows
This is why window functions are more powerful for comparative analysis. The Most Common Window FunctionsROW_NUMBER() - Sequential numbering (1, 2, 3, 4...)
RANK() - Ranking with gaps for ties (1, 2, 2, 4...)
DENSE_RANK() - Ranking without gaps (1, 2, 2, 3...)
LAG() / LEAD() - Access previous/next row values
For "top N within category" questions, ROW_NUMBER() is usually what you want. Try This At Your JobNext time someone asks for "best performers within each category": Think: WINDOW_FUNCTIONS to the rescue! Pattern:
Replace:
This pattern works for any "best within category" business question. Real-World Applications
All of these use the same window function pattern. When to Level UpYou're ready for window functions when you find yourself:
That's when window functions save you hours of work. The Learning CurveWindow functions have different syntax than what you're used to, but the concept is straightforward once you see it in action. Once you understand PARTITION BY (separate ranking windows) and ORDER BY (how to sort within each window), the rest falls into place. Write 3-4 window function queries and it becomes natural. After that, you'll wonder how you ever worked without them. Start with ROW_NUMBER() for ranking. Get comfortable with the pattern. Then explore RANK(), LAG(), LEAD(), and the others as you need them. Before long, you'll be the analyst who delivers complex rankings in minutes while others are still fighting with Excel. Until next time, Brian P.S. Window functions are covered in depth in Module 7 of SQL for Business Impact, where we explore 12 different window function patterns for comparative analysis. If you're ready to level up from intermediate to advanced SQL skills, check out the course at sqlforbusinessimpact.com. P.P.S. What "top N within category" questions do you need to answer at work? Reply and let me know - I might use your scenario in a future deep dive. I read every response. |
Learn to build analytics projects with SQL, Tableau, Excel, and Python. For data analysts looking to level up their career and complete beginners looking to get started. No fluff. No theory. Just step-by-step tutorials anyone can follow.
Hey Reader, Imagine you're a marketing analyst and your marketing director walks over and says: "I need our customers broken into spending tiers (VIP, Standard, and Low Value) so I can send different emails to each group." You have the data. But every customer just has a dollar amount. There's no "tier" column in the database. How do you create categories that don't exist yet? This is where CASE WHEN becomes one of the most useful tools in your SQL toolkit. The problem is that raw data...
Hey Reader, This week's newsletter is different. Not a regular "how to solve problem X with SQL" kinda thing. Because I've realized something: you can write perfect queries and still never get the career impact you want. You need "soft skills" like presenting your results to leadership in addition to "technical skills" like using CTEs and WINDOW functions. Let me show you what I mean. The Scenario Wednesday, 2pm. Q2 review meeting. CMO: "Our booking conversion is down. What's causing it?"...
Hello Reader, One thing before we get into this week's tutorial on the magic of JOINs: I launched a new job board -- just for data people! 🥳 It's called DataJobsOnline.com (creative, I know). And I have been building out the data base of jobs over the past few weeks: 405 Remote Data Analyst Jobs 182 Mid-Level Jobs that require "SQL" 183 Tableau Jobs 38 Data Jobs in London You get the idea...it's a job board! For data professionals like you. If you're not job hunting right now, but know...