Skip to main content

Query Explanation - 3: Finding Customers Who Made a Purchase Every Month for the Last Six Months

 

In this blog post, we will explore how to write a query that identifies customers who have made at least one purchase in every month for the last six months. This type of query is useful in analyzing customer loyalty, engagement, and purchasing frequency over time.

Problem Statement:

We need to find all customers who have made at least one purchase in each of the last six months. This requires tracking customer orders over a rolling six-month period and ensuring that there is a purchase recorded for each month.

Example Schema:

Assume we have the following table:

  1. Orders:
    • OrderID (Primary Key)
    • CustomerID (Foreign Key, links to customer)
    • OrderDate (DateTime)

SQL Query:

To solve this, we will:

  1. Filter orders from the last six months.
  2. Group the results by CustomerID.
  3. Count the distinct months in which each customer has made a purchase.
  4. Use HAVING to ensure that the customer made a purchase in exactly six distinct months.

Here’s the query:

SELECT 
    CustomerID
FROM 
    Orders
WHERE 
    OrderDate >= DATEADD(MONTH, -6, GETDATE())  -- Only consider orders in the last 6 months
GROUP BY 
    CustomerID
HAVING 
    COUNT(DISTINCT DATEPART(MONTH, OrderDate)) = 6;  -- Ensure exactly 6 distinct months of purchases

Detailed Breakdown:

  1. Filtering the Last 6 Months of Data:

    • The WHERE clause filters the data to only include orders placed in the last six months. This is done using the DATEADD() function, which subtracts 6 months from the current date (GETDATE()).
    • DATEADD(MONTH, -6, GETDATE()) dynamically adjusts to always consider the previous 6 months from the current date.
  2. Grouping by Customer:

    • The GROUP BY clause is used to group the results by CustomerID. This ensures that we will be able to analyze each customer's orders independently.
  3. Counting Distinct Months:

    • DATEPART(MONTH, OrderDate) extracts the month part of the OrderDate. By using COUNT(DISTINCT DATEPART(MONTH, OrderDate)), we count how many distinct months the customer made purchases in.
    • The use of DISTINCT ensures that even if a customer made multiple purchases in a single month, it will only count once per month.
  4. HAVING Clause for Exact Month Count:

    • The HAVING clause ensures that the customer has made purchases in exactly six distinct months. If the count is 6, it means the customer made at least one purchase in every month for the last six months.

Example Data:

Let’s say we have the following data in the Orders table:



In this data:

  • CustomerID 101 made purchases in every month from April to September, so they qualify for the query.
  • CustomerID 102 did not make a purchase in all months (they missed some), so they don’t qualify.
  • CustomerID 103 also made purchases in five months but missed April, so they don't qualify.

Example Output:

After running the query, the result would look like this:


Only CustomerID 101 has made a purchase in every month for the last six months.

Key Takeaways:

  • DATEADD and DATEPART Functions: The DATEADD() function is used to calculate a rolling time period (in this case, 6 months), and the DATEPART() function is used to extract the month from a date for comparison.
  • GROUP BY and HAVING: These clauses work together to ensure that customers are grouped by their CustomerID, and the HAVING clause filters the results to only include those who made a purchase in all six months.
  • Counting Distinct Values: The COUNT(DISTINCT DATEPART(MONTH, OrderDate)) ensures that only distinct months are counted, avoiding multiple purchases within the same month from being double-counted.

By using these SQL techniques, we can accurately retrieve customers who have shown consistent purchasing behavior over a specific period.

Comments

Popular posts from this blog

Clean Architecture: What It Is and How It Differs from Microservices

In the tech world, buzzwords like   Clean Architecture   and   Microservices   often dominate discussions about building scalable, maintainable applications. But what exactly is Clean Architecture? How does it compare to Microservices? And most importantly, is it more efficient? Let’s break it all down, from understanding the core principles of Clean Architecture to comparing it with Microservices. By the end of this blog, you’ll know when to use each and why Clean Architecture might just be the silent hero your projects need. What is Clean Architecture? Clean Architecture  is a design paradigm introduced by Robert C. Martin (Uncle Bob) in his book  Clean Architecture: A Craftsman’s Guide to Software Structure and Design . It’s an evolution of layered architecture, focusing on organizing code in a way that makes it  flexible ,  testable , and  easy to maintain . Core Principles of Clean Architecture Dependency Inversion : High-level modules s...

C# : How can we access private method outside class

Introduction In object-oriented programming, encapsulation is a fundamental principle that restricts direct access to the internal implementation details of a class. Private methods, being part of this internal implementation, are designed to be accessible only within the confines of the class they belong to. However, there might be scenarios where you need to access a private method from outside the class. In this blog post, we'll explore several techniques to achieve this in C#. 1. Reflection: A Powerful Yet Delicate Approach Reflection is a mechanism in C# that allows inspecting and interacting with metadata about types, fields, properties, and methods. While it provides a way to access private methods, it should be used cautiously due to its potential impact on maintainability and performance. using System ; using System . Reflection ; public class MyClass { private void PrivateMethod ( ) { Console . WriteLine ( "This is a private method."...

20+ LINQ Concepts with .Net Code

LINQ   (Language Integrated Query) is one of the most powerful features in .NET, providing a unified syntax to query collections, databases, XML, and other data sources. Below are 20+ important LINQ concepts, their explanations, and code snippets to help you understand their usage. 1.  Where  (Filtering) The  Where()  method is used to filter a collection based on a given condition. var numbers = new List < int > { 1 , 2 , 3 , 4 , 5 , 6 } ; var evenNumbers = numbers . Where ( n => n % 2 == 0 ) . ToList ( ) ; // Output: [2, 4, 6] C# Copy 2.  Select  (Projection) The  Select()  method projects each element of a sequence into a new form, allowing transformation of data. var employees = new List < Employee > { /* ... */ } ; var employeeNames = employees . Select ( e => e . Name ) . ToList ( ) ; // Output: List of employee names C# Copy 3.  OrderBy  (Sorting in Ascending Order) The  Or...