Module 4 Lab: Complex Queries
You are officially writing advanced SQL. You understand how to nest queries within other queries, how to build temporary derived tables, and how to use Common Table Expressions (CTEs) to make your code modular and readable.
It’s time to put these skills to the test with a real-world business intelligence task.
The Scenario
The CEO of our E-Commerce platform has asked you to identify our “Whale” customers so we can send them a VIP gift basket.
They have defined a “Whale” as any customer whose total lifetime spending on the platform is greater than $150.
You have two tables:
users(containsidandname)orders(containsid,user_id, andtotal_amount)
Building the Query
To solve this, you must construct a query using a CTE.
Here is your game plan:
- Define a CTE using the
WITHclause. Name the CTEuser_spending. - Inside the CTE, query the
orderstable. Group the data byuser_idand useSUM(total_amount)to calculate the total lifetime spend for each user. Alias that sum aslifetime_spend. - Now, write your main
SELECTstatement below the CTE. - Your main statement should
SELECTthenamefrom theuserstable, and thelifetime_spendfrom your CTE. - To do this, you must
INNER JOINtheuserstable to youruser_spendingCTE using theuser_id. - Finally, add a
WHEREclause to your main query to filter only for rows wherelifetime_spend > 150.
This is a very common pattern in data analytics: group and summarize data in a CTE, then join that summary back to a main table to get human-readable names.
Good luck! Once you’ve identified the Whales, you’ll be ready to dive into the powerful world of Module 5: Window Functions!