Find Top Customer
Orders
that contain the following columns:
OrderId
(int)CustomerId
(int)OrderDate
(datetime)TotalAmount
(money)Orders
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.
Orders
table by OrderDate
to only include orders made in the last 30 days, and then grouping the data by CustomerId
and summing the TotalAmount
column.DATEPART
function 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.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.
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.