The Problem
You have been given a tableOrders that contain the following columns:
OrderId(int)CustomerId(int)OrderDate(datetime)TotalAmount(money)
The Input Data
Here’s the SQL script to create theOrders table and insert some sample data into it:
Orders table contains 15 rows of data. The table has four columns: OrderId, CustomerId, OrderDate, and TotalAmount. Each row represents an order made by a customer.

Expected Output
Here’s the expected output of the SQL query:
Explanation
To solve this challenge, you need to find the top 5 customers who have spent the most money in the last 30 days, subject to the condition that they have made at least one order in each of the last 4 weeks. To accomplish this, you need to perform the following steps:- Calculate the total amount spent by each customer in the last 30 days. You can do this by filtering the
Orderstable byOrderDateto only include orders made in the last 30 days, and then grouping the data byCustomerIdand summing theTotalAmountcolumn. - Determine which customers have made orders in each of the last 4 weeks. To do this, you can use a
DATEPARTfunction to find out the week number from the order date. The distinct count of the week number should be 4 to be considered as the customer has purchased each of the weeks. If a customer has not made an order in each of the last 4 weeks, they should be excluded from the result set. - Order the results by the total amount spent in descending order and return the top 2 rows.
CustomerId and the total amount spent in the last 30 days by each customer who meets the condition of having made at least one order in each of the last 4 weeks.
Solution
Here’s the SQL script that solves the challenge:WHERE clause filters the Orders table to only include orders made in the last 30 days, and the GROUP BY clause groups the data by CustomerId and sums the TotalAmount column.
The outer query then filters the results based on the condition that each customer has made at least one order in each of the last 4 weeks. This is done using a subquery that groups the Orders table by CustomerId. The subquery then checks if the number of distinct week numbers is equal to 4, indicating that the customer has made an order in each of the last 4 weeks.
The results are then ordered by the total amount spent in descending order and the top 2 rows are returned.
