Market Basket Analysis with SQL

Overview

Definition

Market Basket Analysis (MBA) is a data mining technique used by retailers to increase sales by better understanding customer purchasing patterns. It involves analyzing large data sets, such as purchase history, to reveal product groupings, as well as products that are likely to be purchased together.

Example

If a customer buys a notebook, how likely are they going to buy a pen on the same trip? How likely is it that a customer who just bought a shirt will also buy a pair of pants? This technique is a pioneer in the retail sector, solving such scenarios to provide clients with better recommendations. It has been widely used in establishments like theaters, quick food outlets, and clothes stores.


MBA with AdventureWorks2019 database

Let's have a look at the case study in Azure Data Studio on the AdventureWorks2019 database, specifically the FactInternetSales table with two attributes: SalesOrderNumber and ProductKey, to better understand how MBA operates.

Description

  • FactInternetSales table: Sales record through internet channel
    1. SalesOrderNumber: The code indentifies the order
    2. ProductKey: The code indentifies the product
SELECT TOP 10 -- see the first 10 rows of the table
	SalesOrderNumber,
	ProductKey
FROM FactInternetSales;

1. Select the orders having at least two different products

SELECT
	SalesOrderNumber,
	COUNT(ProductKey) AS NumberofProducts
FROM FactInternetSales
GROUP BY SalesOrderNumber
HAVING COUNT(ProductKey) >= 2;

We have the following result:


2. List out the SalesOrderNumber and ProductKey of orders having at least two product keys

SELECT
	OrderList.SalesOrderNumber,
	FIS.ProductKey
FROM
	(SELECT
		SalesOrderNumber,
		COUNT(ProductKey) AS NumberofProducts
	FROM FactInternetSales
	GROUP BY SalesOrderNumber
	HAVING COUNT(ProductKey) >= 2) AS OrderList
JOIN FactInternetSales AS FIS ON Orderlist.SalesOrderNumber = FIS.SalesOrderNumber;

We have the following result:

Notice that all the orders returned have more than 1 product key. Before seeing which combination of two products occurs most frequent, let’s use common table expression (CTE) to use this result for further uses.


3. Create combinations of two products in the same order

WITH OrderTable AS
(SELECT
	OrderList.SalesOrderNumber,
	FIS.ProductKey
FROM
	(SELECT
		SalesOrderNumber,
		COUNT(ProductKey) AS NumberofProducts
	FROM FactInternetSales
	GROUP BY SalesOrderNumber
	HAVING COUNT(ProductKey) >= 2) AS OrderList
JOIN FactInternetSales AS FIS ON Orderlist.SalesOrderNumber = FIS.SalesOrderNumber)

SELECT 
	Order1.SalesOrderNumber,
	Order1.ProductKey AS Product1,
	Order2.ProductKey AS Product2
FROM OrderTable AS Order1
JOIN OrderTable AS Order2 
  ON Order1.SalesOrderNumber = Order2.SalesOrderNumber
    AND Order1.ProductKey < Order2.ProductKey;

We self join the temporary “OrderTable” table (CTE) to view every 2 products that occur in the same order. Pay attention to the “ON” statement where we specify condition to avoid duplicates.

  • Order1.ProductKey < Order2.ProductKey
    This is to avoid duplicates. If this condition does not exist, the result will be:

Look at the first and the third record where Product1 equals Product2 and vice versa. This makes the result is twice as long as it should be. Therefore, removing duplicates by using second condition is a must.

This is the result without duplicates:


4. Calculate the frequency of a pair of two products

WITH OrderTable AS
(SELECT
    OrderList.SalesOrderNumber,
    FIS.ProductKey
FROM
    (SELECT
        SalesOrderNumber,
        COUNT(ProductKey) AS NumberofProducts
    FROM FactInternetSales
    GROUP BY SalesOrderNumber
    HAVING COUNT(ProductKey) >= 2) AS OrderList
JOIN FactInternetSales AS FIS ON Orderlist.SalesOrderNumber = FIS.SalesOrderNumber)

SELECT 
    Order1.ProductKey AS Product1,
    Order2.ProductKey AS Product2,
    COUNT(*) AS Frequency
FROM OrderTable AS Order1
JOIN OrderTable AS Order2 
    ON Order1.SalesOrderNumber = Order2.SalesOrderNumber
    AND Order1.ProductKey < Order2.ProductKey
GROUP BY
	Order1.ProductKey,
	Order2.ProductKey
ORDER BY Frequency;

We have the following result:

From the result, we can interpret that if a customer buys product 477, they are most likely to buy product 478 and 479. Therefore, recommending customers to buy these two products would be likely to improve sales revenue.


Conclusion

MBA is an extremely powerful technique that a number of companies now are using to anticipate the interest of customers in order to suggest them the most relevant product besides what they chose to optimize the revenue. With only a few lines of code, SQL helps us to extract the data we need and make the right business decisions.


Reference

Manh Hung