<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Adedamola A. Adeagbo on Medium]]></title>
        <description><![CDATA[Stories by Adedamola A. Adeagbo on Medium]]></description>
        <link>https://medium.com/@damoladeagbo?source=rss-ea1964676623------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Tk1p7rMMktCV73XSec0M1w.jpeg</url>
            <title>Stories by Adedamola A. Adeagbo on Medium</title>
            <link>https://medium.com/@damoladeagbo?source=rss-ea1964676623------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 03:27:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@damoladeagbo/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Investigating a Scale Model Company Sales Data to Identify Customer Behaviour & Product Purchases]]></title>
            <link>https://medium.com/@damoladeagbo/investigating-a-scale-model-company-sales-data-to-identify-customer-behaviour-product-purchases-eba1167f8c9e?source=rss-ea1964676623------2</link>
            <guid isPermaLink="false">https://medium.com/p/eba1167f8c9e</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[etl-pipeline]]></category>
            <category><![CDATA[marketing-analytics]]></category>
            <category><![CDATA[exploratory-data-analysis]]></category>
            <dc:creator><![CDATA[Adedamola A. Adeagbo]]></dc:creator>
            <pubDate>Sun, 23 Feb 2025 12:01:20 GMT</pubDate>
            <atom:updated>2025-02-24T12:41:56.053Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uJiYUFOQzaDZOApArmx5JQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@felifox?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Felix Fuchs</a> on <a href="https://unsplash.com/photos/cars-parked-in-front-of-building-during-daytime-PoPsSRju8Y8?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>In the ever-evolving landscape of data-driven decision-making, uncovering customer behavior and purchase trends is pivotal for strategic growth. As a data analyst, I embarked on a comprehensive research project for <strong>Company X </strong>(lets call them company X for now), a scale model manufacturer renowned for its exquisite replicas of classic cars, planes, motorcycles, ships, trains, trucks, and buses. This project aimed to analyze and understand the company’s sales data, providing actionable insights into customer behavior and product purchase patterns.</p><p>Using the power of <strong>SQL</strong> for efficient data extraction and manipulation, alongside <strong>Python</strong> for advanced data analysis and visualization, an in-depth exploration of the data was conducted.</p><h3>Main Objective</h3><p>The objective of this project was clear: to identify trends, preferences, and opportunities that could shape Company X’s marketing, inventory management, and product development strategies.</p><p>In other words, analysing the product, order, and customer data, will aid in identifying which products to prioritise, how to segment customers, and how much to spend acquiring new customers.</p><p>This research delved into key questions such as:</p><ul><li>Which product categories drive the highest revenue?</li><li>What purchasing behaviours distinguish loyal customers from casual buyers?</li><li>How do seasonal trends and customer demographics influence sales?</li></ul><p>The analysis of this project was grouped into four (4) segments; Data Exploration and Cleaning, Sales Analysis, Product Analysis and Customer Analysis. By doing this, further insights and recommendations to properly improve their marketing and drive sales will be generated.</p><p>For the Data Exploration and Cleaning, the following outcomes are expected:</p><ul><li>All data tables cleaned and free of errors and duplicates.</li><li>Cleaning dataset to remove unnecessary columns and null values.</li><li>Updated fields with correct information and date formats.</li></ul><p>For Sales Analysis;</p><ul><li>Product sales and revenue generated by each product line .</li><li>Top-selling and low-inventory products based on purchasing cost, revenue and profit.</li><li>Revenue and profit generated by sales rep, sales manager, territory, and product vendor</li><li>Average revenue by month and recurring monthly revenue.</li></ul><p>For Product Analysis;</p><ul><li>Total orders recorded for each product and product line.</li><li>Total quantity sold for each product and product line.</li><li>Top performing and underperforming products based on quantity sold.</li><li>Shipped orders by status, product line, country, month and year.</li></ul><p>For Customer Analysis;</p><ul><li>Segmented customers by purchase history and location to target marketing efforts.</li><li>Total orders and revenue by customers.</li><li>Customers with the most and least transactions, and total customer transactions by year.</li><li>Total customers who exceeded their credit limit.</li><li>Average revenue per customer and customer lifetime value.</li></ul><h3>Available Data</h3><p>For this case study, the eight (8) datasets provided will be used to solve all of the questions and generate the necessary insights for the stakeholders involved. The datasets are:</p><ul><li><strong>Customers Table: </strong>This table provides an overview into customer details such as customer name, address, city, sales rep employee number, country, and credit limit.</li><li><strong>Employees Table: </strong>This table contains information on employees first and last name, email, office code, reports to, and job title.</li><li><strong>Products Table: </strong>This table contains the code, name, line, vendor, description, quantity in stock, buy price and market retail sale price for each product.</li><li><strong>Product Lines Table: </strong>This table has just 2 columns; the product line (or product class), and product description.</li><li><strong>Orders Table: </strong>This table gives an overview of the order number, order date, required date, shipped date, status and customer number.</li><li><strong>Order Details Table: </strong>This table contains the order number, product code, quantity order, price sold, and order line number.</li><li><strong>Payments Table: </strong>This table is a summary of the payment details; customer number, checking number, payment date, and amount paid.</li><li><strong>Offices Table: </strong>This table focuses on the phone number, address, city, postal code, country and territory of sale office locations.</li></ul><h3>Data Importing Process (MySQL)</h3><p>To begin, an automated Extract, Transform, Load (ETL) process needs to be implemented. The ETL process involves, extracting and importing the datasets (All in CSV format) into MySQL where each table will be cleaned; errors and duplicates removed, primary keys and foreign keys will be allocated, uniformity in data types and columns, then after ready to use for analysis.</p><p>The first step in implementing this solution is to create a schema where each dataset will be added into. After creating the schema, each individual table is created with values inserted into them. Below is the schema and table creation process.</p><p>Full importing query with table values:</p><p><a href="https://github.com/Dedamola1/Customer_and_Product_Analysis/blob/main/Data%20Importing.sql">Customer_and_Product_Analysis/Data Importing.sql at main · Dedamola1/Customer_and_Product_Analysis</a></p><h3>Enterprise Relationship Diagram</h3><p>The enterprise relationship was created to show the relationship between all the nine datasets. The image below shows a visual representation of each table relationship.</p><ul><li>Customers and Employees table are linked on a many-to-one relationship.</li><li>Customers and Payments table are linked on a one-to-many relationship.</li><li>Customers and Orders table are linked on a one-to-many relationship.</li><li>Employees and Offices table are linked on a many-to-one relationship.</li><li>Orders and Order Details table are linked on a one-to-many relationship.</li><li>Orders Details and Products table are linked on a many-to-one relationship.</li><li>Products and Product Lines table are linked on a many-to-one relationship.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ByWRqTgKppPmnjaoi9piug.png" /><figcaption>Company X Enterprise Relationship Diagram</figcaption></figure><h3>Data Exploratory Process (MySQL)</h3><p>After the data importing and cleaning done using the ETL process, the datasets are ready to be explored and analysed on SQL.</p><p>The data exploratory process involves analysing the datasets to obtain the desired outcomes for each analysis (Data Exploration and Cleaning, Sales Analysis, Product Analysis and Customer Analysis) using single SQL queries.</p><h4>Data Exploration and Cleaning</h4><p>The SQL queries below offer a detailed exploration and cleaning of each of the datasets within the database. This process focuses on cleaning all data tables to ensure they are free of errors and duplicates, removing all unnecessary columns and null values, and updating all fields with correct information and date formats.</p><p>This exploration and cleaning prepares the datasets for further analysis to be carried out.</p><pre>USE db_schema;<br><br>-- Cleaning new customers table<br>ALTER TABLE customers_new<br>DROP COLUMN state,<br>DROP COLUMN phone,<br>DROP COLUMN addressline2;<br><br>-- Cleaning new offices table<br>ALTER TABLE offices_new<br>DROP COLUMN addressline2,<br>DROP COLUMN state;<br><br>UPDATE offices_new<br>SET territory = &#39;APAC&#39;<br>WHERE country = &#39;Japan&#39;;<br><br>UPDATE offices_new<br>SET territory = &#39;North America&#39;<br>WHERE country = &#39;USA&#39;;<br><br>-- Cleaning new orders table<br>ALTER TABLE orders_new<br>DROP COLUMN comments;<br><br>-- Cleaning new productlines table<br>ALTER TABLE productlines_new<br>DROP COLUMN htmldescription,<br>DROP COLUMN image;<br><br>-- Cleaning new products table<br>ALTER TABLE products_new<br>DROP COLUMN productdescription;<br><br>-- Cleaning new employees table<br>UPDATE employees_new<br>SET `jobTitle` = &#39;Sales Manager (EMEA)&#39;<br>WHERE `employeeNumber` = 1102;<br><br>-- Removing Duplicates within Tables<br>-- Customers table<br>WITH customers_CTE AS (<br>    SELECT *,<br>        ROW_NUMBER() OVER(PARTITION BY customerNumber, customerName, contactFirstName, contactLastName) AS Row_Num<br>    FROM customers_new<br>)<br>SELECT *<br>FROM customers_CTE<br>WHERE Row_Num &gt; 1;<br><br>-- Orderdetails table<br>WITH orderdetails_CTE AS (<br>    SELECT *,<br>        ROW_NUMBER() OVER(PARTITION BY orderNumber, productCode, orderLineNumber) AS Row_Num<br>    FROM orderdetails<br>)<br>SELECT *<br>FROM orderdetails_CTE<br>WHERE Row_Num &gt; 1;<br><br>-- Orders table<br>WITH orders_CTE AS (<br>    SELECT *,<br>        ROW_NUMBER() OVER(PARTITION BY orderNumber, customerNumber) AS Row_Num<br>    FROM orders_new<br>)<br>SELECT *<br>FROM orders_CTE<br>WHERE Row_Num &gt; 1;<br><br>-- Payments table<br>WITH payments_CTE AS (<br>    SELECT *,<br>        ROW_NUMBER() OVER(PARTITION BY customerNumber, checkNumber) AS Row_Num<br>    FROM payments<br>)<br>SELECT *<br>FROM payments_CTE<br>WHERE Row_Num &gt; 1;</pre><h4>Sales Analysis</h4><p>For this analysis, the aim is to uncover insights on revenue and sales generated on a monthly basis from orders, order details and products dataset. These queries focus on the which product categories drive the highest revenue, where are most products ordered from, average revenue by month and monthly recurring revenue.</p><pre>USE db_schema;<br><br>-- Total revenue generated<br>SELECT SUM(`quantityOrdered` * `priceEach`) AS revenue<br>FROM orderdetails od<br>JOIN orders_new odn <br>    ON odn.`orderNumber` = od.`orderNumber`<br>WHERE odn.`status` IN (&#39;Shipped&#39;, &#39;Resolved&#39;)<br>;<br><br><br>-- Revenue generated by each product line<br>SELECT `productLine`,<br>        SUM(`quantityOrdered` * `priceEach`) AS revenue<br>FROM products_new pn<br>JOIN orderdetails od<br>    ON od.`productCode` = pn.`productCode`<br>JOIN orders_new odn <br>    ON odn.`orderNumber` = od.`orderNumber`<br>WHERE odn.`status` IN (&#39;Shipped&#39;, &#39;Resolved&#39;)<br>GROUP BY `productLine`<br>ORDER BY revenue DESC<br>;<br><br>-- Top 5 &amp; Bottom 5 products by revenue<br>(SELECT `productName`,<br>        SUM(`quantityOrdered` * `priceEach`) AS revenue,<br>        &#39;Top&#39; AS position<br>FROM products_new pn<br>JOIN orderdetails od<br>    ON od.`productCode` = pn.`productCode`<br>JOIN orders_new odn <br>    ON odn.`orderNumber` = od.`orderNumber`<br>WHERE odn.`status` IN (&#39;Shipped&#39;, &#39;Resolved&#39;)<br>GROUP BY `productName`<br>ORDER BY revenue DESC<br>LIMIT 5)<br>UNION ALL<br>(SELECT `productName`,<br>        SUM(`quantityOrdered` * `priceEach`) AS revenue,<br>        &#39;Bottom&#39; AS position<br>FROM products_new pn<br>JOIN orderdetails od<br>    ON od.`productCode` = pn.`productCode`<br>JOIN orders_new odn <br>    ON odn.`orderNumber` = od.`orderNumber`<br>WHERE odn.`status` IN (&#39;Shipped&#39;, &#39;Resolved&#39;)<br>GROUP BY `productName`<br>ORDER BY revenue ASC<br>LIMIT 5)<br>;<br><br>-- Top product in product line by revenue<br>WITH product_CTE AS (<br>    SELECT `productLine`,<br>            `productName`,<br>            SUM(`quantityOrdered` * `priceEach`) AS revenue,<br>            ROW_NUMBER() OVER(PARTITION BY `productLine` ORDER BY SUM(`quantityOrdered` * `priceEach`) DESC) AS row_num<br>    FROM products_new pn<br>    JOIN orderdetails od<br>        ON od.`productCode` = pn.`productCode`<br>    JOIN orders_new odn <br>    ON odn.`orderNumber` = od.`orderNumber`<br>    WHERE odn.`status` IN (&#39;Shipped&#39;, &#39;Resolved&#39;)<br>    GROUP BY `productLine`, `productName`<br>)<br>SELECT `productLine`,<br>        `productName`,<br>        revenue<br>FROM `product_CTE`<br>WHERE row_num = 1<br>;</pre><p>Full sales analysis sql queries repo on Github:</p><p><a href="https://github.com/Dedamola1/Customer_and_Product_Analysis/blob/main/Sales%20Analysis.sql">Customer_and_Product_Analysis/Sales Analysis.sql at main · Dedamola1/Customer_and_Product_Analysis</a></p><h4>Product Analysis</h4><p>This analysis focuses on analysing the products, product lines, orders, and order details dataset to identify top-selling and low-inventory products and product lines. The SQL queries provide a more detailed view on customer order trend by month when purchasing products, most products ordered and sold, top destination for products shipped.</p><p>Overall, this analysis provides a better understanding as to which products or product lines to market to customers and the ones avoid.</p><pre><br>USE db_schema;<br><br>-- Total orders recorded for each product line<br>SELECT `productLine`,<br>        COUNT(od.`orderNumber`) AS total_Orders<br>FROM products_new pn<br>JOIN orderdetails od<br>    ON od.`productCode` = pn.`productCode`<br>JOIN orders_new odn<br>    ON odn.`orderNumber` = od.`orderNumber`<br>GROUP BY `productLine`<br>ORDER BY total_orders DESC<br>;<br><br>-- Quantity sold for each product line<br>SELECT `productLine`,<br>        SUM(`quantityOrdered`) AS total_quantity_ordered<br>FROM products_new pn<br>JOIN orderdetails od<br>    ON od.`productCode` = pn.`productCode`<br>JOIN orders_new odn <br>    ON odn.`orderNumber` = od.`orderNumber` <br>WHERE odn.`status` IN (&#39;Shipped&#39;, &#39;Resolved&#39;)<br>GROUP BY `productLine`<br>ORDER BY total_quantity_ordered DESC<br>;<br><br>-- Top 5 &amp; Bottom 5 products by quantity sold<br>(SELECT `productName`,<br>        SUM(`quantityOrdered`) AS total_quantity_sold,<br>        &#39;Top&#39; AS position<br>FROM products_new pn<br>JOIN orderdetails od<br>    ON od.`productCode` = pn.`productCode`<br>JOIN orders_new odn <br>    ON odn.`orderNumber` = od.`orderNumber` <br>WHERE odn.`status` IN (&#39;Shipped&#39;, &#39;Resolved&#39;)<br>GROUP BY `productName`, `productLine`<br>ORDER BY total_quantity_sold DESC<br>LIMIT 5)<br>UNION ALL<br>(SELECT `productName`,<br>        SUM(`quantityOrdered`) AS total_quantity_sold,<br>        &#39;Bottom&#39; AS position<br>FROM products_new pn<br>JOIN orderdetails od<br>    ON od.`productCode` = pn.`productCode`<br>JOIN orders_new odn <br>    ON odn.`orderNumber` = od.`orderNumber` <br>WHERE odn.`status` IN (&#39;Shipped&#39;, &#39;Resolved&#39;)<br>GROUP BY `productName`, `productLine`<br>ORDER BY total_quantity_sold ASC<br>LIMIT 5)<br>;<br><br>-- Top product in product line by quantity sold<br>WITH product_CTE AS (<br>    SELECT `productName`,<br>            `productLine`,<br>            SUM(`quantityOrdered`) AS total_quantity_sold,<br>            ROW_NUMBER () OVER(PARTITION BY `productLine` ORDER BY SUM(`quantityOrdered`) DESC) AS row_num<br>    FROM products_new pn<br>    JOIN orderdetails od<br>        ON od.`productCode` = pn.`productCode`<br>    JOIN orders_new odn <br>        ON odn.`orderNumber` = od.`orderNumber`<br>    GROUP BY `productName`, `productLine`<br>)<br>SELECT `productLine`,<br>        `productName`,<br>        total_quantity_sold<br>FROM `product_CTE`<br>WHERE row_num = 1<br>;</pre><p>Full product analysis sql queries repo on Github:</p><p><a href="https://github.com/Dedamola1/Customer_and_Product_Analysis/blob/main/Products%20Analysis.sql">Customer_and_Product_Analysis/Products Analysis.sql at main · Dedamola1/Customer_and_Product_Analysis</a></p><h4>Customer Analysis</h4><p>The customer analysis main focus is on segmenting customers by purchase history and location to target marketing efforts. The SQL queries calculate key metrics like customer lifetime value, customers who exceed credit limit, average revenue per customer (ARPC), and total transactions by year.</p><p>These insights will aid in optimising acquisition spend and identifying key target points for customers.</p><pre>USE db_schema;<br><br>-- Customer distribution by country<br>SELECT country,<br>        COUNT(`customerNumber`) AS total_customers<br>FROM customers_new<br>GROUP BY country<br>ORDER BY total_customers DESC<br>;<br><br>-- Total count of customers above &amp; below credit limit<br>(SELECT COUNT(`customerNumber`) As customersExceedingLimit,<br>        &#39;Above Credit Limit&#39; AS credit_limit<br>FROM (<br>        SELECT c.`customerNumber`,<br>                `customerName`,<br>                `creditLimit`,<br>                SUM(amount) as totalSpend<br>        FROM customers_new c <br>        JOIN payments p <br>                ON p.`customerNumber` = c.`customerNumber`<br>        GROUP BY c.`customerNumber`,<br>                `customerName`,<br>                `creditLimit`<br>        ORDER BY c.`customerNumber`<br>) as agg_table2<br>WHERE totalSpend &gt; `creditLimit`)<br>UNION ALL<br>(SELECT COUNT(`customerNumber`) As customersExceedingLimit,<br>        &#39;Below Credit Limit&#39; AS credit_limit<br>FROM (<br>        SELECT c.`customerNumber`,<br>                `customerName`,<br>                `creditLimit`,<br>                SUM(amount) as totalSpend<br>        FROM customers_new c <br>        JOIN payments p <br>                ON p.`customerNumber` = c.`customerNumber`<br>        GROUP BY c.`customerNumber`,<br>                `customerName`,<br>                `creditLimit`<br>        ORDER BY c.`customerNumber`<br>) as agg_table3<br>WHERE totalSpend &lt; `creditLimit`)<br>;<br><br>-- Customers name who exceed their credit limit<br>SELECT `customerName`<br>FROM (<br>        SELECT c.`customerNumber`,<br>                `customerName`,<br>                `creditLimit`,<br>                SUM(amount) as totalSpend<br>        FROM customers_new c <br>        JOIN payments p <br>        ON p.`customerNumber` = c.`customerNumber`<br>        GROUP BY c.`customerNumber`,<br>                `customerName`,<br>                `creditLimit`<br>        ORDER BY c.`customerNumber`<br>) as agg_table4<br>WHERE totalSpend &gt; `creditLimit`<br>;<br><br>-- Average revenue per customer (ARPC) in 2003, 2004 and 2005<br>(SELECT ROUND(revenue / customers,2) AS AverageRevenuePerCustomer,<br>        &#39;2003&#39; AS Year<br>FROM (<br>        SELECT SUM(od.`quantityOrdered` * od.`priceEach`) AS revenue,<br>                COUNT(DISTINCT(`customerName`)) AS customers<br>        FROM orderdetails od<br>        JOIN orders_new odn<br>                ON odn.`orderNumber` = od.`orderNumber`<br>        JOIN customers_new c <br>                ON c.`customerNumber` = odn.`customerNumber`<br>        WHERE odn.`status` IN (&#39;Shipped&#39;, &#39;Resolved&#39;) AND YEAR(`shippedDate`) = 2003<br>) AS agg_table5)<br>UNION ALL<br>(SELECT ROUND(revenue / customers,2) AS AverageRevenuePerCustomer,<br>        &#39;2004&#39; AS Year<br>FROM (<br>        SELECT SUM(od.`quantityOrdered` * od.`priceEach`) AS revenue,<br>                COUNT(DISTINCT(`customerName`)) AS customers<br>        FROM orderdetails od<br>        JOIN orders_new odn<br>                ON odn.`orderNumber` = od.`orderNumber`<br>        JOIN customers_new c <br>                ON c.`customerNumber` = odn.`customerNumber`<br>        WHERE odn.`status` IN (&#39;Shipped&#39;, &#39;Resolved&#39;) AND YEAR(`shippedDate`) = 2004<br>) AS agg_table5)<br>UNION ALL<br>(SELECT ROUND(revenue / customers,2) AS AverageRevenuePerCustomer,<br>        &#39;2005&#39; AS Year<br>FROM (<br>        SELECT SUM(od.`quantityOrdered` * od.`priceEach`) AS revenue,<br>                COUNT(DISTINCT(`customerName`)) AS customers<br>        FROM orderdetails od<br>        JOIN orders_new odn<br>                ON odn.`orderNumber` = od.`orderNumber`<br>        JOIN customers_new c <br>                ON c.`customerNumber` = odn.`customerNumber`<br>        WHERE odn.`status` IN (&#39;Shipped&#39;, &#39;Resolved&#39;) AND YEAR(`shippedDate`) = 2005<br>) AS agg_table5)<br>;</pre><p>Full customer analysis sql queries repo on Github:</p><p><a href="https://github.com/Dedamola1/Customer_and_Product_Analysis/blob/main/Customers%20Analysis.sql">Customer_and_Product_Analysis/Customers Analysis.sql at main · Dedamola1/Customer_and_Product_Analysis</a></p><h3>Data Visualisation with Python</h3><p>For this analysis, <strong>Python </strong>was used for advanced data analysis and visualisation. Using the following libraries; <em>Pandas, Seaborn and Matplotlib</em>, Python effectively generated plots for each of the analysis conducted in SQL.</p><p>Python was connected to the SQL database, using “<em>%load_ext sql” </em>and<em> “%sql mysql+pymysql”</em> commands. Each of the SQL queries in the Sales, Products and Customer analysis were visualised in its own Jupyter notebook — Sales EDA, Product EDA and Customer EDA.</p><p><strong>Sales EDA in Python</strong></p><p>Below are the visualisations of the sql queries using Python. Python made use of <em>Seaborn</em> to visualise the column charts, bar charts and line graphs.</p><pre><br>!pip install --upgrade ipython-sql<br>!pip install --upgrade prettytable<br>!pip install --upgrade pymysql<br><br># import all packages and set plots to be embedded inline<br>import numpy as np<br>import pandas as pd<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br><br>%load_ext sql<br><br>from prettytable import PrettyTable, PLAIN_COLUMNS<br># Set PLAIN_COLUMNS as default<br>%config SqlMagic.style = &#39;PLAIN_COLUMNS&#39;<br><br>%sql mysql+pymysql://root:***@localhost/db_schema<br><br># Total revenue by product line<br># Run the SQL query and load data into a DataFrame<br>data = %sql SELECT `productLine`, SUM(`quantityOrdered` * `priceEach`) AS revenue FROM products_new pn JOIN orderdetails od ON od.`productCode` = pn.`productCode` JOIN orders_new odn ON odn.`orderNumber` = od.`orderNumber` WHERE odn.`status` IN (&#39;Shipped&#39;, &#39;Resolved&#39;) GROUP BY `productLine` ORDER BY revenue DESC;<br>df = data.DataFrame()<br># Create the barplot without hue<br>plt.figure(figsize=(12, 6))<br>g = sns.barplot(data=df, y=&#39;revenue&#39;, x=&#39;productLine&#39;, palette=&quot;deep&quot;,<br>                hue=&#39;revenue&#39;, legend=False)<br># Set axis labels and title<br>g.set_xlabel(&quot;Product Line&quot;)<br>g.set_ylabel(&quot;Amount (USD)&quot;)<br>plt.title(&quot;Total Revenue by Product Line&quot;.upper(),<br>          fontsize=14)<br># Show plot<br>plt.show()<br><br># Top five (5) products by revenue<br># Run the SQL query and load data into a DataFrame<br>data = %sql SELECT `productName`,SUM(`quantityOrdered` * `priceEach`) AS revenue,&#39;Top&#39; AS position FROM products_new pn JOIN orderdetails od ON od.`productCode` = pn.`productCode` JOIN orders_new odn ON odn.`orderNumber` = od.`orderNumber` WHERE odn.`status` IN (&#39;Shipped&#39;, &#39;Resolved&#39;) GROUP BY `productName` ORDER BY revenue DESC LIMIT 5; <br>df = data.DataFrame()<br># Create the barplot without hue<br>plt.figure(figsize=(14, 6))<br>g = sns.barplot(data=df, y=&#39;revenue&#39;, x=&#39;productName&#39;, palette=&quot;colorblind&quot;,<br>                hue=&#39;revenue&#39;, legend=False)<br># Set axis labels and title<br>g.set_xlabel(&quot;Product&quot;)<br>g.set_ylabel(&quot;Amount (USD)&quot;)<br>plt.title(&quot;Top 5 Products by Revenue&quot;.upper(),<br>          fontsize=14)<br># Show plot<br>plt.show()<br><br># Bottom five (5) products by revenue<br># Run the SQL query and load data into a DataFrame<br>data = %sql SELECT `productName`, SUM(`quantityOrdered` * `priceEach`) AS revenue FROM products_new pn JOIN orderdetails od ON od.`productCode` = pn.`productCode` JOIN orders_new odn ON odn.`orderNumber` = od.`orderNumber` WHERE odn.`status` IN (&#39;Shipped&#39;, &#39;Resolved&#39;) GROUP BY `productName` ORDER BY revenue ASC LIMIT 5;<br>df = data.DataFrame()<br># Create the barplot without hue<br>plt.figure(figsize=(14, 6))<br>g = sns.barplot(data=df, y=&#39;revenue&#39;, x=&#39;productName&#39;, palette=&quot;muted&quot;,<br>                hue=&#39;revenue&#39;, legend=False)<br># Set axis labels and title<br>g.set_xlabel(&quot;Product&quot;)<br>g.set_ylabel(&quot;Amount (USD)&quot;)<br>plt.title(&quot;Bottom 5 Products by Revenue&quot;.upper())<br># Show plot<br>plt.show()<br><br># Revenue, purchasing cost and profit by product line<br># Run the SQL query and load data into a DataFrame<br>data = %sql SELECT `productLine`, SUM(od.`quantityOrdered` * pn.`buyPrice`) AS Purchasing_Cost, SUM((od.`priceEach` - pn.`buyPrice`) * od.`quantityOrdered`) AS Profit, SUM(od.`quantityOrdered` * od.`priceEach`) AS Revenue FROM products_new pn JOIN orderdetails od ON od.`productCode` = pn.`productCode` JOIN orders_new odn ON odn.`orderNumber` = od.`orderNumber` WHERE odn.`status` IN (&#39;Shipped&#39;, &#39;Resolved&#39;) GROUP BY `productLine` ORDER BY profit DESC;<br>df = data.DataFrame()<br># Melt the DataFrame to long format for easier plotting<br>df_melted = df.melt(id_vars=&#39;productLine&#39;, <br>                    value_vars=[&#39;Revenue&#39;,&#39;Purchasing_Cost&#39;, &#39;Profit&#39;], <br>                    var_name=&#39;Metric&#39;, <br>                    value_name=&#39;Value&#39;)<br># Plot grouped bar chart<br>plt.figure(figsize=(14, 8))<br>g = sns.barplot(data=df_melted, x=&#39;productLine&#39;, y=&#39;Value&#39;, <br>                hue=&#39;Metric&#39;, palette=&#39;muted&#39;)<br># Set axis labels and title<br>g.set_xlabel(&quot;Product Line&quot;, fontsize=12)<br>g.set_ylabel(&quot;Amount (USD)&quot;, fontsize=12)<br>plt.title(&quot;Revenue, Purchasing Cost and Profit by Product Line&quot;.upper(), <br>          fontsize=16)<br># Rotate x-axis labels for better readability<br>#plt.xticks(rotation=45)<br># Show legend and plot<br>plt.legend(title=&#39;Metric&#39;, loc=&#39;upper right&#39;, fontsize=12)<br>plt.tight_layout()<br>plt.show()</pre><p>Full Python Sales EDA repo on github:</p><p><a href="https://github.com/Dedamola1/Customer_and_Product_Analysis/blob/main/Sales%20EDA.ipynb">Customer_and_Product_Analysis/Sales EDA.ipynb at main · Dedamola1/Customer_and_Product_Analysis</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yATGEnRJ1_5qn746-iFCUA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*ovJWseIfexz3RcTeQ4zhHg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6ANMiaOzW-jvrBQLRCf-fA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M1fOEYsTAQZYivc8WdrT7g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mm9iAchMVr3sjMJcxuOD3Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DMAsyxonnu1sKcYgOmu-1w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yAFNypfL6PxsOBujbZBhog.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dynqw0i-jWNeKYC4SuygUw.png" /></figure><p><strong>Product EDA in Python</strong></p><p>Below are the visualisations of the sql queries using Python. Python made use of <em>Seaborn</em> to visualise the column charts, bar charts and pie charts for this analysis.</p><pre><br># import all packages and set plots to be embedded inline<br>import numpy as np<br>import pandas as pd<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br><br>%load_ext sql<br><br>from prettytable import PrettyTable, PLAIN_COLUMNS<br># Set PLAIN_COLUMNS as default<br>%config SqlMagic.style = &#39;PLAIN_COLUMNS&#39;<br><br>%sql mysql+pymysql://root:***@localhost/db_schema<br><br># Total orders by product line<br># Run the SQL query and load data into a DataFrame<br>data = %sql SELECT `productLine`, COUNT(od.`orderNumber`) AS total_Orders FROM products_new pn JOIN orderdetails od ON od.`productCode` = pn.`productCode`JOIN orders_new odn ON odn.`orderNumber` = od.`orderNumber` GROUP BY `productLine` ORDER BY total_orders DESC;<br>df = data.DataFrame()<br># Create the barplot without hue<br>plt.figure(figsize=(12, 6))<br>g = sns.barplot(data=df, y=&#39;total_Orders&#39;, x=&#39;productLine&#39;, palette=&quot;deep&quot;,<br>                hue=&#39;total_Orders&#39;, legend=False)<br># Set axis labels and title<br>g.set_xlabel(&quot;Product Line&quot;)<br>g.set_ylabel(&quot;Orders&quot;)<br>plt.title(&quot;Total Orders by Product Line&quot;.upper())<br># Show plot<br>plt.show()<br><br># Total orders by top twenty (20) products<br># Run the SQL query and load data into a DataFrame<br>data = %sql SELECT `productName`, COUNT(od.`orderNumber`) AS total_Orders FROM products_new pn JOIN orderdetails od ON od.`productCode` = pn.`productCode` JOIN orders_new odn ON odn.`orderNumber` = od.`orderNumber` GROUP BY `productName` ORDER BY total_orders DESC LIMIT 20;<br>df = data.DataFrame()<br># Create the barplot without hue<br>plt.figure(figsize=(16, 10))<br>g = sns.barplot(data=df, y=&#39;productName&#39;, x=&#39;total_Orders&#39;, palette=&quot;dark&quot;,<br>                hue=&#39;productName&#39;, legend=False)<br># Set axis labels and title<br>g.set_xlabel(&quot;Orders&quot;, fontsize=16)<br>g.set_ylabel(&quot;Product&quot;, fontsize=16)<br>plt.title(&quot;Total Orders by Top 20 Products&quot;.upper(), fontsize=16)<br># Show plot<br>plt.show()<br><br># Total quantity sold by product line<br># Run the SQL query and load data into a DataFrame<br>data = %sql SELECT `productLine`, SUM(`quantityOrdered`) AS total_quantity_sold FROM products_new pn JOIN orderdetails od ON od.`productCode` = pn.`productCode` JOIN orders_new odn ON odn.`orderNumber` = od.`orderNumber` WHERE odn.`status` IN (&#39;Shipped&#39;, &#39;Resolved&#39;) GROUP BY `productLine` ORDER BY total_quantity_sold DESC;<br>df = data.DataFrame()<br># Create the barplot without hue<br>plt.figure(figsize=(16, 10))<br>g = sns.barplot(data=df, y=&#39;productLine&#39;, x=&#39;total_quantity_sold&#39;, palette=&quot;muted&quot;,<br>                hue=&#39;productLine&#39;, legend=False)<br># Set axis labels and title<br>g.set_xlabel(&quot;Quantity Sold&quot;, fontsize=16)<br>g.set_ylabel(&quot;Product Line&quot;, fontsize=16)<br>plt.title(&quot;Total Quantity Sold by Product Line&quot;.upper(), fontsize=16)<br># Show plot<br>plt.show()<br><br># Total orders by status<br># Run the SQL query and load data into a DataFrame<br>data = %sql SELECT odn.status, COUNT(od.`orderNumber`) AS total_orders, ROUND((COUNT(od.`orderNumber`) * 100.0) / SUM(COUNT(od.`orderNumber`)) OVER (),1) AS orders_percentage FROM orderdetails od JOIN orders_new odn ON odn.`orderNumber` = od.`orderNumber`  GROUP BY odn.status ORDER BY total_orders DESC;<br>df = data.DataFrame()<br># Set Seaborn theme<br>sns.set_theme(style=&quot;whitegrid&quot;)<br># Plotting the pie chart<br>plt.figure(figsize=(16, 12))<br>plt.pie(df[&#39;orders_percentage&#39;], labels=df[&#39;status&#39;], autopct=&#39;%1.1f%%&#39;, startangle=140, colors=sns.color_palette(&quot;bright&quot;, len(df)))<br># Title and display<br>plt.title(&quot;Total Orders by Status&quot;.upper())<br>plt.legend(title=&#39;status&#39;, loc=&#39;upper right&#39;, fontsize=12)<br>plt.show()</pre><p>Full Python Product EDA repo on github:</p><p><a href="https://github.com/Dedamola1/Customer_and_Product_Analysis/blob/main/Products%20EDA.ipynb">Customer_and_Product_Analysis/Products EDA.ipynb at main · Dedamola1/Customer_and_Product_Analysis</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8abHWuS6NOf5Z_V5J1hXsg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EgeCpw5vgYA98ebT4sm3cg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ohqvlzdBhZH-3UK4K_xGVQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wy6z0e9FQiD0GK0ym8heDg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*KSoGQ41Ps2gx-4LgFh7r5g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fNmjVYhjU9eUK7RZLO6BOw.png" /></figure><p><strong>Customer EDA in Python</strong></p><p>Below are the visualisations of the sql queries using Python. Python made use of <em>Seaborn</em> to visualise the column charts, bar charts, pie charts and line graphs for this analysis.</p><pre><br># import all packages and set plots to be embedded inline<br>import numpy as np<br>import pandas as pd<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br><br>%load_ext sql<br><br>from prettytable import PrettyTable, PLAIN_COLUMNS<br># Set PLAIN_COLUMNS as default<br>%config SqlMagic.style = &#39;PLAIN_COLUMNS&#39;<br><br>%sql mysql+pymysql://root:***@localhost/db_schema<br><br># Total customers by country<br># Run the SQL query and load data into a DataFrame<br>data = %sql SELECT country, COUNT(`customerNumber`) AS total_customers FROM customers_new GROUP BY country ORDER BY total_customers DESC;<br>df = data.DataFrame()<br># Create the barplot without hue<br>plt.figure(figsize=(14, 12))<br>g = sns.barplot(data=df, y=&#39;country&#39;, x=&#39;total_customers&#39;, palette=&quot;bright&quot;,<br>                hue=&#39;country&#39;, legend=False)<br># Set axis labels and title<br>g.set_xlabel(&quot;Total Customers&quot;, fontsize=12)<br>g.set_ylabel(&quot;Country&quot;, fontsize=12)<br>plt.title(&quot;Total Customers by Country&quot;.upper(), fontsize=14)<br># Show plot<br>plt.show()<br><br># Total revenue by top ten (10) customers<br># Run the SQL query and load data into a DataFrame<br>data = %sql SELECT `customerName`,SUM(od.`quantityOrdered` * od.`priceEach`) AS revenue FROM products_new pn JOIN orderdetails od ON od.`productCode` = pn.`productCode` JOIN orders_new odn ON odn.`orderNumber` = od.`orderNumber`JOIN customers_new c ON c.`customerNumber` = odn.`customerNumber` WHERE odn.`status` IN (&#39;Shipped&#39;, &#39;Resolved&#39;) GROUP BY `customerName`ORDER BY revenue DESC LIMIT 10;<br>df = data.DataFrame()<br># Create the barplot without hue<br>plt.figure(figsize=(18, 12))<br>g = sns.barplot(data=df, y=&#39;customerName&#39;, x=&#39;revenue&#39;, palette=&quot;muted&quot;,<br>                hue=&#39;customerName&#39;, legend=False)<br># Set axis labels and title<br>g.set_xlabel(&quot;Revenue&quot;, fontsize=14)<br>g.set_ylabel(&quot;Customer Name&quot;, fontsize=14)<br>plt.title(&quot;Total Revenue by Top 10 Customers&quot;.upper(), fontsize=16)<br># Show plot<br>plt.show()<br><br># Total customer transactions by year <br># Run the SQL query and load data into a DataFrame<br>data = %sql SELECT DISTINCT(YEAR(`paymentDate`)) AS year, COUNT(`customerNumber`) AS customerTransactions FROM payments GROUP BY YEAR(`paymentDate`);<br>df = data.DataFrame()<br># Create the barplot without hue<br>plt.figure(figsize=(18, 10))<br>g = sns.barplot(data=df, y=&#39;customerTransactions&#39;, x=&#39;year&#39;, palette=&quot;deep&quot;,<br>                hue=&#39;customerTransactions&#39;, legend=False)<br># Set axis labels and title<br>g.set_xlabel(&quot;Year&quot;, fontsize=14)<br>g.set_ylabel(&quot;Customer Transactions&quot;, fontsize=14)<br>plt.title(&quot;Total Customer Transactions by Year&quot;.upper(), fontsize=16)<br># Show plot<br>plt.show()<br></pre><p>Full Python Customer EDA repo on github:</p><p><a href="https://github.com/Dedamola1/Customer_and_Product_Analysis/blob/main/Customers%20EDA.ipynb">Customer_and_Product_Analysis/Customers EDA.ipynb at main · Dedamola1/Customer_and_Product_Analysis</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Gudg0iv7pou0C6FbH_osA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZwYp-HlZw0UzFHAm3Couug.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*jEF7IWYUJcgT8zxN_DUR0A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sdLWf1tOs8zJZaoofI2IxA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*shz55eN1Xu4bHyeb7GWJdQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*Oci1PPAn_OJP_CdPxbxaig.png" /></figure><h3>Results &amp; Insights</h3><p>The analysis of the scale model company (<strong>Company X)</strong> using SQL &amp; Python yielded several detailed insights and outcomes, below are the resulting insights.</p><p><strong>Product Line Performance:</strong></p><ul><li>Classic Cars dominates revenue generation at $3.6M, more than double the next category — Vintage Cars at $1.7M.</li><li>Motorcycles, Trucks/Buses, and Planes form the middle tier ($0.8M-$1.1M).</li><li>Ships and Trains have significantly lower revenue ($0.6M and $0.2M respectively).</li><li>Classic Cars lead both in shipped orders (~950) and total quantity sold (~32,000 units), Vintage Cars are the second strongest category with ~600 shipped orders and ~22,000 units.</li><li>Significant gap between top two categories and others — Motorcycles, Planes, and Trucks/Buses form the middle tier with 300–350 shipped orders each.</li></ul><p><strong>Individual Product Performance:</strong></p><p>Top 5 Products:</p><ul><li>1992 Ferrari 360 Spider red leads with ~$260K revenue.</li><li>High-end vintage and classic cars dominate the top revenue products.</li><li>Premium brands (Ferrari, Alpine Renault, Harley-Davidson) show strong performance.</li><li>Price points in top products range from $150K-$260K.</li></ul><p>Bottom 5 Products:</p><ul><li>Revenue range of $26K-$33K for bottom performers.</li><li>Mix of vintage American and European models.</li><li>Notable presence of luxury brands even in lower-performing products.</li><li>Smaller price variance among bottom performers compared to top products.</li></ul><p><strong>Geographic Revenue Distribution &amp; Market Presence:</strong></p><ul><li>USA is the dominant market with ~$3M in revenue, while Spain and France form strong secondary markets (~$1M each).</li><li>Asian markets (Japan, Singapore, Hong Kong) show lower revenue contribution.</li><li>USA also dominates with the highest number of customers, followed by Germany and France as key markets.</li><li>USA dominates the market with over 800 shipped orders, while Spain and France form a strong secondary market with around 300–400 orders each.</li><li>The business appears to have global reach across 25 countries</li></ul><p><strong>Revenue Analysis &amp; Trends:</strong></p><ul><li>Average revenue per customer peaked in 2004 at approximately $50,000.</li><li>Consistent seasonal pattern shows stronger performance in spring months.</li><li>2003 shows more volatility in monthly revenue compared to 2004–2005.</li><li>Lower revenue periods typically occur in September-October.</li></ul><p><strong>Order Volume Patterns &amp; Status Distributions:</strong></p><ul><li>The vast majority of orders (92.4%) have been successfully shipped.</li><li>Cancelled orders at approximately 2.6%, resolved issues around 2%, and orders on hold, in process, or disputed make up the remaining ~3%</li><li>Euro+ Shopping Channel leads in order volume, consistent with their revenue leadership.</li><li>Mini Gifts Distributors Ltd. maintains high order volumes, indicating consistent business.</li><li>Order distribution among top customers is more balanced than revenue distribution.</li></ul><p><strong>Top Customer Revenue Analysis:</strong></p><ul><li>Euro+ Shopping Channel and Mini Gifts Distributors Ltd. are significantly ahead of other customers in revenue.</li><li>There’s a considerable revenue gap between the top 2 customers and the rest.</li><li>Australian Collectors Co. and Muscle Machine Inc. form a second tier of valuable customers.</li></ul><p><strong>Profitability Analysis:</strong></p><ul><li>All product lines maintain positive profit margins.</li><li>Classic Cars shows the highest absolute profit (~$1.4M).</li><li>Profit margins appear relatively consistent across categories (around 35–40%).</li><li>Lower revenue categories (Ships, Trains) maintain proportional profitability.</li></ul><p><strong>Credit Profile:</strong></p><ul><li>Customer base is almost evenly split between credit limits.</li><li>53.1% of customers are below credit limit, and 46.9% of customers are above credit limit.</li></ul><h4>Key Business Insights:</h4><p><strong>Product Strategy: </strong>Maintain premium product positioning and consider expanding successful product categories</p><p><strong>Customer Concentration Risk:</strong> Heavy dependence on top two customers could be a business risk, need to create a strategic plan to diversify the customer base</p><p><strong>Market Opportunity: </strong>Strong presence in developed markets (European markets) suggests potential for emerging market expansion and also eoom for growth in Asian markets.</p><p><strong>Business Efficiency: </strong>The high shipping completion rate (92.4%) suggests excellent operational efficiency.</p><p><strong>Category Development:</strong> Opportunity to grow smaller categories like Trains and Ships.</p><p><strong>Credit Management: </strong>High proportion of customers above credit limit suggests need for better credit control.</p><p><strong>Performance Trends:</strong> Declining average revenue per customer needs investigation, possible need for customer retention and growth strategies.</p><h3>Recommendations</h3><p><strong>Geographic Market Development:</strong></p><ul><li>Create targeted marketing campaigns for the strong European markets (Spain, France)</li><li>Develop localized marketing content and customer support for these regions</li><li>Consider special promotions for emerging markets like Australia and UK to build on existing success</li><li>Explore untapped potential in Asian markets, particularly focusing on the collector communities in Japan and Singapore</li></ul><p><strong>Product Line Optimization:</strong></p><ul><li>Increase focus on Classic and Vintage Cars marketing as they’re the primary revenue drivers</li><li>Create exclusive or limited edition releases of the most popular models (like the Ferrari 360 Spider)</li><li>Bundle complementary products (e.g., classic car with period-appropriate accessories)</li><li>Consider developing themed collections (e.g., “Golden Age of American Automobiles” or “European Luxury Classics”)</li></ul><p><strong>Customer Engagement Strategies:</strong></p><ul><li>Implement a loyalty program specifically for collectors</li><li>Create content around the history and stories behind the models to increase engagement</li><li>Develop a community platform for collectors to share their collections and experiences</li><li>Host virtual or physical collector meetups in key markets</li></ul><p><strong>Operational Improvements:</strong></p><ul><li>Maintain the excellent shipping success rate (92.4%) through continued quality control</li><li>Address the causes of cancellations (2.6%) through better inventory management</li><li>Implement a proactive communication strategy for delayed orders to prevent disputes</li><li>Consider premium shipping options for high-value collectors’ items</li></ul><p><strong>Digital Marketing Initiatives:</strong></p><ul><li>Create detailed product storylines for each model, emphasizing historical significance</li><li>Develop social media content showcasing detailed craftsmanship</li><li>Use email marketing to announce new releases and share collection care tips</li><li>Implement retargeting campaigns focusing on abandoned carts</li></ul><h3>Conclusion</h3><p>The scale model company (<strong>Company X</strong>) shows strong market presence with excellent operational efficiency, demonstrated by the high order fulfillment rate. The business has established a solid foundation in the classic and vintage car segments, which serve as its primary revenue drivers. There’s a clear geographic concentration in the US market, with promising growth in European markets.</p><p>The company’s success with high-end collectible models suggests a knowledgeable customer base willing to invest in quality pieces. This presents opportunities for premium product development and expanded collector services. The diverse product range, from luxury cars to commercial vehicles, provides multiple growth avenues.</p><p>Key areas for improvement include:</p><ul><li>Geographic market diversification</li><li>Strengthening smaller product categories</li><li>Enhanced customer engagement programs</li><li>Digital presence optimization</li></ul><p>With targeted marketing efforts focusing on key markets and product lines, while maintaining the high operational standards, the company is well-positioned for sustainable growth. The challenge will be balancing expansion with the quality and attention to detail that has built their current success.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eba1167f8c9e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Analysing Aggregated Metrics to Generate Insights for a Digital Marketing Agency using MySQL]]></title>
            <link>https://medium.com/@damoladeagbo/analyzing-aggregated-metrics-to-generate-insights-for-a-digital-marketing-agency-using-mysql-7be0bec53714?source=rss-ea1964676623------2</link>
            <guid isPermaLink="false">https://medium.com/p/7be0bec53714</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[market-research-reports]]></category>
            <category><![CDATA[digital-marketing-agency]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data-exploration]]></category>
            <dc:creator><![CDATA[Adedamola A. Adeagbo]]></dc:creator>
            <pubDate>Sun, 01 Sep 2024 20:32:45 GMT</pubDate>
            <atom:updated>2024-09-02T10:28:55.761Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hm8aCVRVrDalYEAHDLKr0Q.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@xingchenyan?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Xingchen Yan</a> on <a href="https://unsplash.com/photos/an-aerial-view-of-a-city-with-tall-buildings-2u3sZzp2ACA?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>Fresh Segments, a digital marketing agency that helps other businesses analyse trends in online ad click behaviour for their unique customer base. At Fresh Segments, clients share their customer lists with the Fresh Segments team who then aggregate interest metrics and generate a single dataset worth of metrics for further analysis.</p><p>In particular — the composition and rankings for different interests are provided for each client showing the proportion of their customer list who interacted with online assets related to each interest for each month.</p><p>For this case study, Fresh Segments will be analysing the aggregated metrics for a specific major client of Fresh Segments which makes up a large proportion of their customer base.</p><h3>Primary Objective</h3><p>Previously stated above, the aim of this project is to analyse the aggregated metrics for a major client and to provide high level insights about their customer list, segments, indexing and their interests.</p><p>The analysis of this project was grouped into four (4) segments; Data Exploration and Cleansing, Interest Analysis, Segments Analysis and Index Analysis. By doing this, further insights and recommendations to properly improve their marketing and drive sales will be generated.</p><p>For the Data Exploration and Cleansing, the following outcomes are expected:</p><ul><li>An updated interest metrics dataset with a modified month-year column of date data type and the start of the month.</li><li>Total count of records for each month-year value sorted in chronological order (earliest to latest) with the null values appearing first.</li><li>Total interest values existing in the interest metrics dataset but not in the interest map dataset, and vice-versa.</li><li>A summarised table highlighting the id values in the interest map dataset by its total record count.</li><li>A joined output table including all columns from interest metrics and interest map except from the id column.</li><li>Records in the joined table where the month-year value is before the created at value from the interest map dataset.</li></ul><p>For the Interest Analysis;</p><ul><li>Total interests present in all month-year dates.</li><li>Cumulative percentage of all records starting at 14 months which total months value passes the 90% cumulative percentage value.</li><li>Removed interest id values lower than the total months above.</li><li>Unique interests present each month.</li></ul><p>For the Segment Analysis;</p><ul><li>Top 10 and bottom 10 interests which have the largest composition values in any month-year.</li><li>Top 5 Interests with the lowest average ranking value.</li><li>Top 5 interests with the largest standard deviation in their percentile ranking value.</li><li>Minimum and maximum percentile ranking values for each interest above and its corresponding month-year.</li><li>Customers in this segment based off their composition and ranking values ranked from highest to lowest.</li></ul><p>For the Index Analysis;</p><ul><li>Top 10 interests by the average composition for each month.</li><li>Interest that appears the most often from the top 10 interests above.</li><li>Average of the average composition for the top 10 interests for each month.</li><li>3 month rolling average of the max average composition value from September 2018 to August 2019 including previous top ranking interests.</li></ul><h3>Available Data</h3><p>For this case study the two (2) datasets mentioned above will be used to solve all of the questions and generate the necessary insights for the stakeholders involved.</p><ol><li><strong>Interest Metrics:</strong> This table contains information about the aggregated interest metrics for the client. This table contains the following columns; interest_id, index_value, composition, ranking, percentile_ranking, and month year. Each record in this table represents the performance of a specific interest_id based on the client’s customer base interest measured through clicks and interactions with specific targeted advertising content.</li><li><strong>Interest Map: </strong>This mapping table links the interest_id with their relevant interest information such as the interest_name and the interest_summary.</li></ol><h3>Data Importing Process (MySQL)</h3><p>To begin, an automated Extract, Transform, Load (ETL) process needs to be implemented. The ETL process involves, extracting and importing the datasets (All in CSV format) into MySQL where each table will be cleaned; errors and duplicates removed, primary keys and foreign keys will be allocated, uniformity in data types and columns, then after ready to use for analysis.</p><p>The first step in implementing this solution is to create a “fresh_segments” schema where each dataset will be added into. After creating the schema, each individual table is created with values inserted into them. Below is the schema and table creation process.</p><pre>CREATE SCHEMA fresh_segments;<br><br>USE fresh_segments;<br><br>CREATE TABLE fresh_segments.interest_map (<br>  id INTEGER,<br>  interest_name TEXT,<br>  interest_summary TEXT,<br>  created_at TIMESTAMP,<br>  last_modified TIMESTAMP<br>);<br><br>-- update the null values<br>UPDATE fresh_segments.interest_map<br>SET interest_summary = NULL<br>WHERE interest_summary = &#39;&#39;;<br><br>CREATE TABLE fresh_segments.interest_metrics (<br>  month_no VARCHAR(4),<br>  year_no VARCHAR(4),<br>  month_year VARCHAR(7),<br>  interest_id VARCHAR(5),<br>  composition FLOAT,<br>  index_value FLOAT,<br>  ranking INTEGER,<br>  percentile_ranking FLOAT<br>);<br><br>-- update NULL values<br>UPDATE fresh_segments.interest_metrics<br>SET month_no = CASE WHEN month_no = &#39;NULL&#39; THEN NULL <br>     ELSE CAST(month_no AS UNSIGNED) <br>    END;<br><br>UPDATE fresh_segments.interest_metrics<br>SET year_no = CASE WHEN year_no = &#39;NULL&#39; THEN NULL <br>       ELSE CAST(year_no AS UNSIGNED) <br>     END;<br><br>UPDATE fresh_segments.interest_metrics<br>SET month_year = NULL<br>WHERE month_year = &#39;NULL&#39;;<br><br>UPDATE fresh_segments.interest_metrics<br>SET interest_id = NULL<br>WHERE interest_id = &#39;NULL&#39;;</pre><p>Full importing query with table values:</p><p><a href="https://github.com/Dedamola1/Fresh-Segments-Analysis/blob/main/FSA_Importing_and_Cleaning.sql">Fresh-Segments-Analysis/FSA_Importing_and_Cleaning.sql at main · Dedamola1/Fresh-Segments-Analysis</a></p><h3>Enterprise Relationship Diagram</h3><p>The enterprise relationship was created to show the relationship between the two fresh segments datasets. The image below shows a visual representation of each table relationship.</p><ul><li>Interest metrics and interest map datasets are linked on a many-to-one relationship.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*5pIdMJoAfnXjTpL5HlpRAA.png" /><figcaption>Fresh Segments Enterprise Relationship Diagram</figcaption></figure><h3>Data Exploratory Process (MySQL)</h3><p>After the data importing and cleaning done using the ETL process, the datasets are ready to be explored and analysed on SQL.</p><p>The data exploratory process involves using each of the two datasets to answer each of the required questions for each analysis (Data Exploration and Cleansing, Interest Analysis, Segment Analysis and Index Analysis) using single SQL queries.</p><h4>Data Exploration and Cleansing</h4><p>The SQL queries below offer a detailed exploration of the major client from the Fresh Segments’ Agency database. The queries focus on understanding the interest metrics dataset, calculating the specific count of each interest record, the null percentage in the table, interest ids present in the interest metrics dataset and not in the interest map dataset and vice versa. This exploration and cleansing prepares the datasets for further analysis to be carried out.</p><pre>USE fresh_segments;<br><br>-- Updating the interest_metrics table by modifying the month_year column to be a date data type<br>ALTER TABLE fresh_segments.interest_metrics<br>ADD COLUMN month_year_backup VARCHAR(255);<br><br>ALTER TABLE fresh_segments.interest_metrics<br>MODIFY COLUMN month_year VARCHAR(20);<br><br>UPDATE fresh_segments.interest_metrics<br>SET month_year_backup = CONCAT(&#39;01-&#39;, month_year);<br><br>UPDATE fresh_segments.interest_metrics <br>SET month_year = STR_TO_DATE(month_year_backup, &#39;%d-%m-%Y&#39;);<br><br>#UPDATE fresh_segments.interest_metrics<br>#SET month_year_backup = DATE_FORMAT(STR_TO_DATE(month_year_backup, &#39;%d-%m-%Y&#39;), &#39;%m/%d/%Y&#39;);<br><br>#UPDATE fresh_segments.interest_metrics <br>#SET month_year_backup = DATE_FORMAT(STR_TO_DATE(month_year_backup, &#39;%m/%d/%Y&#39;), &#39;%d-%m-%Y&#39;);<br><br>ALTER TABLE fresh_segments.interest_metrics<br>MODIFY COLUMN month_year DATE;<br><br>ALTER TABLE fresh_segments.interest_metrics<br>DROP COLUMN month_year_backup;<br><br>-- Count of records for each month_year value sorted in chronological order (earliest to latest)<br>SELECT month_year, <br>    COUNT(*) AS count_of_records<br>FROM Fresh_segments.interest_metrics<br>GROUP BY month_year<br>ORDER BY month_year IS NULL DESC;<br><br>-- Null percentage in interest metrics table<br>SELECT <br>  ROUND(100 * (SUM(CASE WHEN interest_id IS NULL THEN 1 END) * 1.0 / COUNT(*)),2) AS null_perc<br>FROM fresh_segments.interest_metrics;<br><br>DELETE FROM fresh_segments.interest_metrics<br>WHERE interest_id IS NULL;<br><br>-- Interest_id values present in interest_metrics table but not in the interest_map table and vice-versa<br>SELECT COUNT(DISTINCT im.interest_id) AS missing_interest_ids<br>FROM Fresh_segments.interest_metrics im<br>LEFT JOIN Fresh_segments.interest_map mp<br>ON im.interest_id = mp.id<br>WHERE mp.id IS NULL;<br><br>SELECT COUNT(DISTINCT mp.id) AS missing_ids<br>FROM Fresh_segments.interest_map mp<br>LEFT JOIN Fresh_segments.interest_metrics im<br>ON mp.id = im.interest_id<br>WHERE im.interest_id IS NULL;<br><br>-- Summarized id values in the interest_map by its total record count in this table<br>SELECT id, <br>    interest_name,<br>    COUNT(*) AS total_count<br>FROM fresh_segments.interest_map mp<br>JOIN fresh_segments.interest_metrics im<br>  ON mp.id = im.interest_id<br>GROUP BY id, interest_name<br>ORDER BY total_count DESC, id;<br><br>-- Joined output including all columns from interest_metrics and all columns from interest_map except from the id column.<br>SELECT im.*,<br>  mp.interest_name,<br>        mp.interest_summary,<br>        mp.created_at,<br>        mp.last_modified<br>FROM Fresh_segments.interest_metrics im<br>INNER JOIN Fresh_segments.interest_map mp<br>ON im.interest_id = mp.id<br>WHERE interest_id = 21246 AND month_year IS NOT NULL;<br><br>-- Records in the joined table where the month_year value is before the created_at value from the interest_map table<br>SELECT *<br>FROM fresh_segments.interest_map mp<br>INNER JOIN fresh_segments.interest_metrics im<br>  ON mp.id = im.interest_id<br>WHERE im.month_year &lt; mp.created_at;</pre><h4>Interest Analysis</h4><p>For this analysis, the aim is to uncover insights on interests on a month to month basis from the interest metrics dataset. These queries focus on the interests that have been present during the given timeframe (from July 2018 to August 2019), calculating the cumulative percentage of records above 90%, identifying the unique interests present in each month and unique patterns specific to each month.</p><pre>USE fresh_segments;<br><br>-- Interests have been present in all month_year dates<br>SELECT <br>   COUNT(DISTINCT month_year) AS unique_month_year_count, <br>   COUNT(DISTINCT interest_id) AS unique_interest_id_count<br>FROM fresh_segments.interest_metrics;<br><br>WITH interest_cte AS (<br>SELECT <br>   interest_id, <br>   COUNT(DISTINCT month_year) AS total_months<br>FROM fresh_segments.interest_metrics<br>WHERE month_year IS NOT NULL<br>GROUP BY interest_id<br>)<br>SELECT <br>   total_months,<br>   COUNT(DISTINCT interest_id) AS total_interests_present<br>FROM interest_cte <br>WHERE total_months = 14<br>GROUP BY total_months;<br><br>-- Cumulative percentage of all records starting at 14 months which total_months value passes the 90% cumulative percentage value<br>WITH cte_interest_months AS (<br> SELECT<br>  interest_id,<br>     COUNT(DISTINCT month_year) AS total_months <br> FROM fresh_segments.interest_metrics<br> WHERE interest_id IS NOT NULL<br> GROUP BY interest_id<br>),<br>cte_interest_counts AS (<br> SELECT<br>  total_months,<br>  COUNT(DISTINCT interest_id) AS interest_count<br> FROM cte_interest_months<br> GROUP BY total_months<br>    ORDER BY total_months DESC<br>),<br>cumulative_data AS(<br>SELECT <br> total_months,<br>    ROUND(100 * SUM(interest_count) OVER (ORDER BY total_months DESC) / (SUM(interest_count) OVER ()),2) AS cumulative_perc<br>FROM cte_interest_counts<br>)<br>SELECT *<br>FROM cumulative_data<br>WHERE cumulative_perc &gt; 90;<br><br>-- Removing all interest_id values which are lower than the total_months value above<br>WITH interest_cte AS(<br> SELECT <br>    interest_id, <br>    COUNT(DISTINCT month_year) AS total_months<br> FROM fresh_segments.interest_metrics<br> WHERE month_year IS NOT NULL<br> GROUP BY interest_id<br>)<br>SELECT COUNT(*) AS removed_data_points<br>FROM interest_cte<br>WHERE total_months &gt; 6;<br><br>--  How many unique interests are there for each month after removing these interests?<br>WITH interest_cte AS(<br> SELECT <br>    interest_id, <br>    COUNT(DISTINCT month_year) AS total_months<br> FROM fresh_segments.interest_metrics<br> WHERE month_year IS NOT NULL <br> GROUP BY interest_id<br>)<br>SELECT total_months,<br>  CASE WHEN total_months &lt;= 6 THEN COUNT(DISTINCT interest_id) ELSE 0 END AS unique_interest_count<br>FROM interest_cte<br>GROUP BY total_months;</pre><h4>Segment Analysis</h4><p>This analysis focuses on filtering the interest ids based on composition values and rankings. The analysis aims to provide insights into top and bottom performers, interests with the lowest average rankings, interests with the largest standard deviation in their percentile rankings, as well as minimum and maximum percentile ranking for each interest and its corresponding month year. This analysis also provides a better understanding as to which products or services to market to customers and the ones avoid.</p><pre>USE fresh_segments;<br><br>--  Top 10 and bottom 10 interests which have the largest composition values in any month_year<br>WITH filtered_interest_cte AS (<br>    SELECT *<br>    FROM fresh_segments.interest_metrics<br>    WHERE month_year IS NOT NULL <br>      AND interest_id NOT IN (<br>   SELECT interest_id<br>   FROM fresh_segments.interest_metrics<br>   WHERE month_year IS NOT NULL <br>   GROUP BY interest_id<br>   HAVING COUNT(DISTINCT month_year) &lt; 6<br>      )<br>),<br>MaxCompositions AS (<br>    SELECT <br>        interest_id,<br>        MAX(composition) AS max_composition_value<br>    FROM filtered_interest_cte<br>    GROUP BY interest_id<br>)<br>-- Top 10 Interests<br>(SELECT<br>    fic.month_year,<br>    fic.interest_id,<br>    ROUND(mc.max_composition_value, 2) AS max_composition_value,<br>    &#39;Top&#39; AS position<br>FROM filtered_interest_cte fic<br>JOIN MaxCompositions mc<br> ON fic.interest_id = mc.interest_id<br>  AND fic.composition = mc.max_composition_value<br>ORDER BY mc.max_composition_value DESC<br>LIMIT 10)<br><br>UNION ALL<br><br>-- Bottom 10 Interests<br>(SELECT<br>    fic.month_year,<br>    fic.interest_id,<br>    ROUND(mc.max_composition_value, 2) AS max_composition_value,<br>    &#39;Bottom&#39; AS position<br>FROM filtered_interest_cte fic<br>JOIN MaxCompositions mc<br> ON fic.interest_id = mc.interest_id<br>  AND fic.composition = mc.max_composition_value<br>ORDER BY mc.max_composition_value ASC<br>LIMIT 10);<br><br>-- Which 5 interests had the lowest average ranking value<br>WITH filtered_interest_cte AS (<br>    SELECT *<br>    FROM fresh_segments.interest_metrics<br>    WHERE month_year IS NOT NULL <br>      AND interest_id NOT IN (<br>   SELECT interest_id<br>   FROM fresh_segments.interest_metrics<br>   WHERE month_year IS NOT NULL <br>   GROUP BY interest_id<br>   HAVING COUNT(DISTINCT month_year) &lt; 6<br>      )<br>)<br>SELECT interest_id,<br>  ROUND(AVG(ranking),2) AS avg_ranking_value<br>FROM filtered_interest_cte<br>GROUP BY interest_id<br>ORDER BY avg_ranking_value DESC<br>LIMIT 5;<br><br>-- Which 5 interests had the largest standard deviation in their percentile_ranking value<br>WITH filtered_interest_cte AS (<br>    SELECT *<br>    FROM fresh_segments.interest_metrics<br>    WHERE month_year IS NOT NULL <br>      AND interest_id NOT IN (<br>   SELECT interest_id<br>   FROM fresh_segments.interest_metrics<br>   WHERE month_year IS NOT NULL <br>   GROUP BY interest_id<br>   HAVING COUNT(DISTINCT month_year) &lt; 6<br>      )<br>)<br>SELECT interest_id,<br>  ROUND(STDDEV_SAMP(percentile_ranking), 2) AS stddev_percentile_ranking<br>FROM filtered_interest_cte<br>GROUP BY interest_id<br>ORDER BY stddev_percentile_ranking DESC<br>LIMIT 5;<br><br>-- Minimum and maximum percentile_ranking values for each interest above and its corresponding year_month<br>WITH filtered_interest_cte AS (<br>    SELECT *<br>    FROM fresh_segments.interest_metrics<br>    WHERE month_year IS NOT NULL <br>      AND interest_id NOT IN (<br>   SELECT interest_id<br>   FROM fresh_segments.interest_metrics<br>   WHERE month_year IS NOT NULL <br>   GROUP BY interest_id<br>   HAVING COUNT(DISTINCT month_year) &lt; 6<br>      )<br>),<br>percentile_ranking_cte AS (<br> SELECT interest_id,<br>   ROUND(STDDEV_SAMP(percentile_ranking), 2) AS stddev_percentile_ranking<br> FROM filtered_interest_cte<br> GROUP BY interest_id<br> ORDER BY stddev_percentile_ranking DESC<br> LIMIT 5<br>)<br>SELECT <br>    prc.interest_id,<br>    ROUND(MIN(fic.percentile_ranking), 2) AS min_percentile_ranking,<br>    (SELECT fic1.month_year <br>  FROM filtered_interest_cte fic1 <br>     WHERE fic1.interest_id = prc.interest_id <br>  AND fic1.percentile_ranking = MIN(fic.percentile_ranking)) AS min_month_year,<br>    ROUND(MAX(fic.percentile_ranking), 2) AS max_percentile_ranking,<br>    (SELECT fic2.month_year <br>  FROM filtered_interest_cte fic2 <br>     WHERE fic2.interest_id = prc.interest_id <br>  AND fic2.percentile_ranking = MAX(fic.percentile_ranking)) AS max_month_year<br>FROM filtered_interest_cte fic<br>JOIN percentile_ranking_cte prc<br> ON prc.interest_id = fic.interest_id<br>GROUP BY prc.interest_id<br>ORDER BY max_percentile_ranking DESC;<br><br>-- Customers in this segment based off their composition and ranking values<br>WITH filtered_interest_cte AS (<br>    SELECT *<br>    FROM fresh_segments.interest_metrics<br>    WHERE month_year IS NOT NULL <br>      AND interest_id NOT IN (<br>   SELECT interest_id<br>   FROM fresh_segments.interest_metrics<br>   WHERE month_year IS NOT NULL <br>   GROUP BY interest_id<br>   HAVING COUNT(DISTINCT month_year) &lt; 6<br>      )<br>)<br>SELECT fic.interest_id,<br>  ROUND(AVG(fic.ranking),2) AS avg_ranking_value,<br>        ROUND(MAX(fic.composition),2) AS max_composition,<br>        im.interest_name<br>FROM filtered_interest_cte fic<br>JOIN fresh_segments.interest_map im<br> ON im.id = fic.interest_id<br>GROUP BY fic.interest_id, im.interest_name<br>ORDER BY avg_ranking_value ASC;</pre><h4>Index Analysis</h4><p>The index analysis strictly focuses on the index value which is a measure that can be used to reverse calculate the average composition for Fresh Segments’ clients. For this analysis, the top interest by average composition for each month, most frequent interests, maximum average composition for each month, and the 3 month rolling average of the max average composition value for each month were the main focus.</p><pre>USE fresh_segments;<br><br>-- Top 10 interests by the average composition for each month<br>WITH AvgCompositionCTE AS (<br>    SELECT<br>        month_year,<br>        interest_id,<br>        ROUND(SUM(composition / index_value), 2) AS avg_composition<br>    FROM fresh_segments.interest_metrics<br>    WHERE index_value != 0 AND month_year IS NOT NULL <br>    GROUP BY month_year, interest_id<br>)<br>SELECT<br>    month_year,<br>    interest_id,<br>    avg_composition<br>FROM AvgCompositionCTE<br>ORDER BY avg_composition DESC<br>LIMIT 10;<br><br>-- Average of the average composition for the top 10 interests for each month<br>WITH AvgCompositionCTE AS (<br>    SELECT<br>        month_year,<br>        interest_id,<br>        ROUND(SUM(composition / index_value), 2) AS avg_composition<br>    FROM fresh_segments.interest_metrics<br>    WHERE index_value != 0 AND month_year IS NOT NULL <br>    GROUP BY month_year, interest_id<br>),<br>Top10AvgComposition AS (<br>    SELECT<br>        month_year,<br>        interest_id,<br>        avg_composition<br>    FROM AvgCompositionCTE<br>    ORDER BY month_year, avg_composition DESC<br>    LIMIT 10<br>)<br>SELECT<br>    ROUND(AVG(avg_composition), 2) AS avg_of_top10_avg_compositions<br>FROM Top10AvgComposition;<br><br>-- 3 month rolling average of the max average composition value from September 2018 to August 2019 <br>WITH AvgCompositionCTE AS (<br>    SELECT<br>        im.month_year,<br>        im.interest_id,<br>        mp.interest_name,<br>        ROUND(SUM(im.composition / im.index_value), 2) AS avg_composition<br>    FROM fresh_segments.interest_metrics im<br>    JOIN fresh_segments.interest_map mp <br>        ON mp.id = im.interest_id<br>    WHERE im.index_value != 0 AND im.month_year IS NOT NULL<br>    GROUP BY im.month_year, im.interest_id, mp.interest_name<br>),<br>MaxAvgCompositionPerMonth AS (<br>    SELECT<br>        month_year,<br>        interest_name,<br>        ROUND(MAX(avg_composition), 2) AS max_avg_composition<br>    FROM AvgCompositionCTE<br>    GROUP BY month_year, interest_name<br>),<br>MaxIndexCompositions AS (<br>    SELECT<br>        month_year,<br>        interest_name,<br>        max_avg_composition,<br>        ROW_NUMBER() OVER (PARTITION BY month_year ORDER BY max_avg_composition DESC) AS rn<br>    FROM MaxAvgCompositionPerMonth<br>),<br>FinalMaxIndexComposition AS (<br> SELECT<br>  month_year,<br>  interest_name,<br>  max_avg_composition AS max_index_composition,<br>  ROUND(AVG(max_avg_composition) <br>     OVER (ORDER BY month_year <br>     ROWS BETWEEN 2 PRECEDING AND CURRENT ROW), 2) AS rolling_avg_3_months<br> FROM MaxIndexCompositions<br> WHERE rn = 1 <br> ORDER BY month_year<br>)<br>SELECT *<br>FROM FinalMaxIndexComposition<br>WHERE month_year BETWEEN &#39;2018-09-01&#39; AND &#39;2019-08-01&#39;;</pre><h3>Results &amp; Insights</h3><ol><li><strong>Interest Trends and Popularity: </strong>Interests with high composition values represent those that were most popular or relevant in that given month. Conversely, those with lower values represent niche or declining interests. Interests with high standard deviations in their rankings indicate that these interests had fluctuating popularity over time, possibly due to seasonal trends, external events, or shifting consumer preferences. The interest with the highest composition consistently over time is likely a strong trend indicator.</li><li><strong>Data Gaps and Completeness</strong>: 5% of interest ids in the interest map dataset are missing in the interest metrics dataset, this gap represents a significant amount of unmonitored or under-analysed interest areas. This discrepancies indicate a loss of potentially valuable insights and suggests the need for a review of the data collection processes.</li><li><strong>Rolling Averages and Market Stability</strong>: The rolling averages showed trends in which certain months had significantly higher max compositions compared to others. Rolling averages with steady increase, indicate growing interest and potentially emerging markets. However, a decreasing trend signal a waning interest that might need addressing through targeted marketing or new strategies.</li><li><strong>Top and Bottom Performers</strong>: Based on the analysis, a particular interest (21057) outperformed others multiple times within the analysed timeframe. Top interest in March 2019 had a max average composition value of 12.5, and the rolling average over the next three months was 11.8, this indicates strong and stable interest.</li></ol><h3>Recommendations:</h3><ol><li><strong>Focus on High-Performing Interests</strong>: Allocate more resources and marketing efforts toward interests that consistently show high composition values. These areas are likely driving significant consumer engagement and revenue.</li><li><strong>Address Volatility in Interests</strong>: For interests with high standard deviations, consider investigating the underlying causes. Are these trends seasonal, or do they react strongly to external factors like media coverage or economic conditions? Developing a strategy that leverages these insights can help capitalise on spikes in interest.</li><li><strong>Improve Data Completeness</strong>: The missing interest ids in the metrics table suggest a need to audit the data collection process. Ensure all relevant interests are being tracked to avoid blind spots in your analysis. Regularly update and review the interest map to ensure that all new or emerging interests are being monitored.</li><li><strong>Utilize Rolling Averages for Strategy Development</strong>: The rolling average analysis is valuable for smoothing out data and identifying true trends. Use this analysis to inform long-term strategy rather than reacting to short-term fluctuations. If the rolling average indicates a growing interest in a specific area, consider investing in long-term content or product development around that theme.</li></ol><h3>Conclusion</h3><p>By combining these insights with the SQL queries and data provided, a robust strategy to capitalise on current trends, address data gaps, and prepare for future shifts in consumer interests can be developed. Regularly updating and refining the data analysis approach will always help in maintaining a competitive edge in understanding and reacting to market dynamics.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7be0bec53714" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Sales Insights and Trends at Clothing Company using SQL & Power BI]]></title>
            <link>https://medium.com/@damoladeagbo/exploring-sales-insights-and-trends-at-clothing-company-using-sql-power-bi-9474b8275d61?source=rss-ea1964676623------2</link>
            <guid isPermaLink="false">https://medium.com/p/9474b8275d61</guid>
            <category><![CDATA[clothing]]></category>
            <category><![CDATA[sql-analysis]]></category>
            <category><![CDATA[data-exploration]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[sales-development]]></category>
            <dc:creator><![CDATA[Adedamola A. Adeagbo]]></dc:creator>
            <pubDate>Fri, 19 Jul 2024 00:34:15 GMT</pubDate>
            <atom:updated>2024-07-19T00:34:15.127Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B-1bgqX89Cu5qQYtJ40Daw.jpeg" /></figure><h3>Introduction</h3><p>Balanced Tree Clothing Company offers a diverse selection of apparel for both men and women, catering to modern adventurers with a focus on high-quality shirts, socks, jeans, and jackets. This analysis delves into the company’s sales data to uncover key insights, trends, and performance metrics over a specified period. By examining revenue, discounts, transaction volume, and product popularity, we aim to provide actionable recommendations for enhancing sales strategies and optimizing product offerings.</p><p>In this case study, the CEO Danny, has provided a total of four (4) datasets — Sales, Product Details, Product Prices and Product Hierarchy. The data spans from January to March, with various data columns such as product name, transaction time, member status, quantity, and price.</p><h3>Project Objective</h3><p>The primary objective of this case study is to analyse their overall sales performance and generate a basic financial report to share with the wider business and improve business decisions. The analysis of this project was grouped into three segments; High Level Sales Analysis, Product Analysis and Transactions Analysis.</p><p>For the High Level Sales Analysis, the following outcomes were expected:</p><ul><li>The total quantity sold for all products.</li><li>The total generated revenue for all products before discounts.</li><li>The total generated revenue for all products after discounts.</li><li>The total discount amount for all products.</li></ul><p>For the Product Analysis:</p><ul><li>Top 3 products by total revenue before discount.</li><li>Total quantity, revenue and discount for each segment.</li><li>Top selling product for each segment.</li><li>Total quantity, revenue and discount for each category.</li><li>Top selling product for each category.</li><li>Percentage split of revenue by product for each segment.</li><li>Percentage split of revenue by segment for each category.</li><li>Percentage split of total revenue by category.</li><li>Total transaction “penetration” for each product (penetration = number of transactions where at least 1 quantity of a product was purchased divided by total number of transactions).</li></ul><p>For the Transactions Analysis:</p><ul><li>How many unique transactions were there?</li><li>Average unique products purchased in each transaction.</li><li>25th, 50th and 75th percentile values for the revenue per transaction.</li><li>Average discount value per transaction.</li><li>Percentage split of all transactions for members vs non-members.</li><li>Average revenue for member transactions and non-member transactions.</li></ul><h3>Available Data</h3><p>For this case study the four (4) datasets mentioned above will be used to solve all of the questions and generate the necessary insights for the stakeholders involved.</p><ol><li>balanced_tree.product_details includes all information about the entire range that Balanced Clothing sells in their store. This dataset contains the product id, price, product name, segment name, category name, style name and style id.</li><li>balanced_tree.sales contains product level information for all the transactions made for Balanced Tree including quantity, price, percentage discount, member status, a transaction ID and also the transaction timestamp.</li><li>balanced_tree.product_hierarchy contains product level information which highlight the product name as “level text” and product category as “level name” with their respective product id.</li><li>balanced_tree.product_pricesincludes all information for the product id and their respective price.</li></ol><h3>Data Importing Process (MySQL)</h3><p>To begin, an automated Extract, Transform, Load (ETL) process needs to be implemented. The ETL process involves, extracting and importing the datasets (All in CSV format) into MySQL where each table will be cleaned; errors and duplicates removed, primary keys and foreign keys will be allocated, uniformity in data types and columns, then after ready to use for analysis.</p><p>The first step in implementing this solution is to create a “balanced_tree” schema where each dataset will be added into. After creating the schema, each individual table is created with values inserted into them. Below is the schema and table creation process.</p><pre>CREATE SCHEMA balanced_tree;<br><br>USE balanced_tree;<br><br>CREATE TABLE balanced_tree.product_hierarchy (<br>  id INTEGER,<br>  parent_id INTEGER,<br>  level_text VARCHAR(19),<br>  level_name VARCHAR(8)<br>);<br><br>CREATE TABLE balanced_tree.product_prices (<br>  id INTEGER,<br>  product_id VARCHAR(6),<br>  price INTEGER<br>);<br><br>CREATE TABLE balanced_tree.product_details (<br>  product_id VARCHAR(6),<br>  price INTEGER,<br>  product_name VARCHAR(32),<br>  category_id INTEGER,<br>  segment_id INTEGER,<br>  style_id INTEGER,<br>  category_name VARCHAR(6),<br>  segment_name VARCHAR(6),<br>  style_name VARCHAR(19)<br>);<br><br>CREATE TABLE balanced_tree.sales (<br>  product_id VARCHAR(6),<br>  quantity INTEGER,<br>  price INTEGER,<br>  discount INTEGER,<br>  member_status BOOLEAN,<br>  transaction_id VARCHAR(6),<br>  start_txn_time TIMESTAMP<br>);</pre><p>Full importing query with table values:</p><p><a href="https://github.com/Dedamola1/Balanced-Tree-Store/blob/main/Balanced_Tree_Importing_and_Cleaning.sql">Balanced-Tree-Store/Balanced_Tree_Importing_and_Cleaning.sql at main · Dedamola1/Balanced-Tree-Store</a></p><h3>Enterprise Relationship Diagram</h3><p>The enterprise relationship was created to show the relationship between each of the four balanced tree datasets. The image below shows a visual representation of each table relationship.</p><ul><li>Sales and Product Details table are linked on a many-to-one relationship.</li><li>Sales and Product Prices table are also linked on a many-to-one relationship.</li><li>Product Prices and Product Hierarchy are linked on a one-to-one relationship.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YeeBdBdL7zw9lMNF7BFqSA.png" /></figure><h3>Data Exploratory Process (MySQL)</h3><p>After the data importing and cleaning done using the ETL process, the datasets are ready to be explored and analyzed on SQL.</p><p>The data exploratory process involves using each of the four datasets to answer each of the required questions for each analysis (High Level Sales, Transactions and Product Analysis) using single SQL queries.</p><h4>High Level Sales Analysis</h4><p>The SQL queries offer a detailed examination of the sales data from the Balanced Tree Clothing Company’s database. The queries focus on calculating key financial and sales metrics, providing a foundational understanding of the company’s performance in terms of quantity sold, revenue generation, and discount allocation.</p><pre>USE balanced_tree;<br><br>-- Total quantity sold for all products<br>SELECT SUM(quantity) AS total_qty<br>FROM balanced_tree.sales;<br><br>-- Total generated revenue for all products before discounts<br>SELECT SUM(quantity * price) AS total_revenue <br>FROM balanced_tree.sales;<br><br>-- Total generated revenue for all products after discounts<br>SELECT SUM((quantity * price) - discount) AS revenue<br>FROM balanced_tree.sales;<br><br>-- Total discount amount for all products<br>SELECT SUM(discount) AS total_discount<br>FROM balanced_tree.sales;</pre><h4>Transactions Analysis</h4><p>For this analysis, the aim is to uncover various transactional insights from the sales data. These queries focus on the number of unique transactions, average products purchased per transaction, revenue distribution, discount values, and the behaviour of members versus non-members.</p><pre>USE balanced_tree;<br><br>-- No of unique transactions<br>SELECT COUNT(DISTINCT transaction_id) AS unique_txns<br>FROM balanced_tree.sales;<br><br>-- Average unique products purchased in each transaction<br>SELECT ROUND(AVG(unique_products),2) AS average_products_purchased <br>FROM (SELECT transaction_id, <br>    COUNT(DISTINCT product_id) AS unique_products<br>  FROM balanced_tree.sales<br>  GROUP BY transaction_id<br>) AS unique_products_per_txn;<br><br>-- 25th, 50th and 75th percentile values for the revenue per transaction<br>WITH revenue_per_txn AS (<br>  SELECT transaction_id, <br>      SUM(quantity * price) AS revenue<br>  FROM balanced_tree.sales<br>  GROUP BY transaction_id<br>),<br>ordered_revenues AS (<br>    SELECT revenue,<br>           NTILE(4) OVER (ORDER BY revenue) AS quartile<br>    FROM revenue_per_txn<br>)<br>SELECT<br>    MAX(CASE WHEN quartile = 1 THEN revenue END) AS 25th_percentile,<br>    MAX(CASE WHEN quartile = 2 THEN revenue END) AS 50th_percentile,<br>    MAX(CASE WHEN quartile = 3 THEN revenue END) AS 75th_percentile<br>FROM ordered_revenues;<br><br>-- Average discount value per transaction<br>SELECT ROUND(AVG(total_discount),2) AS average_discount_value<br>FROM (SELECT transaction_id, <br>    SUM(discount) AS total_discount<br>  FROM balanced_tree.sales<br>  GROUP BY transaction_id<br>) AS discount_per_txn;<br><br>-- Percentage split of all transactions for members vs non-members<br>WITH transaction_members AS (<br>  SELECT <br>   DISTINCT(transaction_id),<br>   member_status<br>  FROM balanced_tree.sales<br>)<br>SELECT <br> COUNT(CASE WHEN member_status = 1 THEN 1 END) AS members_txn,<br> COUNT(CASE WHEN member_status = 0 THEN 1 END) AS non_members_txn,<br> (COUNT(CASE WHEN member_status = 1 THEN 1 END) / (SELECT COUNT(DISTINCT transaction_id) FROM balanced_tree.sales)) * 100 AS members_prcnt,<br> (COUNT(CASE WHEN member_status = 0 THEN 1 END) / (SELECT COUNT(DISTINCT transaction_id) FROM balanced_tree.sales)) * 100 AS non_members_prcnt<br>FROM transaction_members;<br><br>-- Average revenue for member transactions and non-member transactions<br>WITH revenue_per_member AS (<br>  SELECT <br>   DISTINCT(transaction_id),<br>   member_status,<br>   SUM(quantity * price) AS revenue<br>  FROM balanced_tree.sales<br>  GROUP BY transaction_id, member_status<br>)<br>SELECT <br> ROUND(AVG(CASE WHEN member_status = 1 THEN revenue END),2) AS avg_revenue_members,<br> ROUND(AVG(CASE WHEN member_status = 0 THEN revenue END),2) AS avg_revenue_non_members<br>FROM revenue_per_member;</pre><h4>Product Analysis</h4><p>These queries focus on product revenue, quantity sold, discounts, and the segmentation of sales data by product, category, and segment. The analysis aims to provide insights into top-performing products, revenue distribution, and customer transaction behaviour.</p><pre>USE balanced_tree;<br><br>-- Top 3 products by total revenue before discount&#39;<br>SELECT p.product_name AS product,<br>  SUM(s.quantity * s.price) AS revenue<br>FROM sales s<br>JOIN product_details p<br>  ON p.product_id = s.product_id<br>GROUP BY p.product_name<br>ORDER BY revenue DESC<br>LIMIT 3;<br><br>-- Total quantity, revenue and discount for each segment<br>SELECT p.segment_name AS segment,<br>  SUM(quantity) AS total_quantity,<br>        SUM(s.quantity * s.price) AS total_revenue,<br>        SUM(discount) AS total_discount<br>FROM sales s<br>JOIN product_details p<br>  ON p.product_id = s.product_id<br>GROUP BY p.segment_name;<br><br>-- Top selling product for each segment<br>WITH ranked_products AS (<br>    SELECT <br>        p.segment_name AS segment,<br>        p.product_name AS product,<br>        SUM(s.quantity) AS total_quantity_sold,<br>        ROW_NUMBER() OVER (PARTITION BY p.segment_name ORDER BY SUM(s.quantity) DESC) AS row_num<br>    FROM sales s<br>    JOIN product_details p <br>    ON p.product_id = s.product_id<br>    GROUP BY p.segment_name, p.product_name<br>)<br>SELECT <br>    segment,<br>    product,<br>    total_quantity_sold<br>FROM ranked_products<br>WHERE row_num = 1;<br><br>-- Total quantity, revenue and discount for each category<br>SELECT p.category_name AS category,<br>  SUM(quantity) AS total_quantity,<br>        SUM(s.quantity * s.price) AS total_revenue,<br>        SUM(discount) AS total_discount<br>FROM sales s<br>JOIN product_details p<br>  ON p.product_id = s.product_id<br>GROUP BY p.category_name;<br><br>-- Top selling product for each category<br>WITH ranked_products AS (<br>    SELECT p.category_name AS category,<br>   p.product_name AS product,<br>   SUM(s.quantity) AS total_quantity_sold,<br>   ROW_NUMBER() OVER (PARTITION BY p.category_name ORDER BY SUM(s.quantity) DESC) AS row_num<br>    FROM sales s<br>    JOIN product_details p <br>    ON p.product_id = s.product_id<br>    GROUP BY p.category_name, p.product_name<br>)<br>SELECT <br>    category,<br>    product,<br>    total_quantity_sold<br>FROM ranked_products<br>WHERE row_num = 1;<br><br>-- Percentage split of revenue by product for each segment<br>WITH product_revenue AS (<br>    SELECT p.segment_name,<br>   p.product_name,<br>   SUM(s.quantity * s.price) AS revenue,<br>   ROW_NUMBER() OVER (PARTITION BY p.segment_name ORDER BY SUM(s.quantity * s.price) DESC) AS row_num<br>    FROM sales s<br>    JOIN product_details p <br>    ON p.product_id = s.product_id<br>    GROUP BY p.segment_name, p.product_name<br>),<br>segment_totals AS (<br>  SELECT segment_name,<br>   SUM(revenue) AS total_revenue<br>  FROM product_revenue<br>  GROUP BY segment_name<br>)<br>SELECT <br>    pr.segment_name,<br>    pr.product_name,<br>    pr.revenue,<br>    ROUND((CASE WHEN pr.row_num &lt;= 3 THEN pr.revenue / st.total_revenue * 100 ELSE 0 END),2) AS percentage_split<br>FROM product_revenue pr<br>JOIN segment_totals st <br>  ON pr.segment_name = st.segment_name;<br><br>-- Percentage split of revenue by segment for each category<br>WITH segment_revenue AS (<br>   SELECT category_name,<br>     segment_name,<br>     SUM(s.quantity * s.price) AS revenue,<br>     ROW_NUMBER() OVER (PARTITION BY p.category_name ORDER BY SUM(s.quantity * s.price) DESC) AS row_num<br>   FROM sales s<br>   JOIN product_details p <br>      ON p.product_id = s.product_id<br>   GROUP BY category_name, segment_name<br>),<br>category_totals AS (<br>  SELECT category_name,<br>    SUM(revenue) AS total_revenue<br>  FROM segment_revenue<br>  GROUP BY category_name<br>)<br>SELECT s.category_name,<br>  s.segment_name,<br>        s.revenue,<br>        ROUND((CASE WHEN row_num &lt;= 2 THEN s.revenue / ct.total_revenue * 100 ELSE 0 END),2) AS percentage_split<br>FROM segment_revenue s<br>JOIN category_totals ct<br>  ON ct.category_name = s.category_name;<br><br>-- Percentage split of total revenue by category<br>WITH category_revenue AS (<br>  SELECT p.category_name,<br>    SUM(s.quantity * s.price) AS revenue<br>  FROM sales s<br>  JOIN product_details p <br>     ON p.product_id = s.product_id<br>  GROUP BY p.category_name<br>)<br>SELECT category_name,<br>  revenue,<br>        ROUND((revenue / (SELECT SUM(quantity * price) FROM balanced_tree.sales) * 100),2) AS percentage_split<br>FROM category_revenue;<br><br>-- Total transaction “penetration” for each product<br>WITH product_transactions AS (<br>   SELECT product_name,<br>     COUNT(transaction_id) AS transactions<br>   FROM sales s<br>   JOIN product_details p <br>      ON p.product_id = s.product_id<br>   GROUP BY product_name<br>)<br>SELECT product_name,<br>  transactions,<br>  ROUND((transactions / (SELECT COUNT(DISTINCT transaction_id) FROM balanced_tree.sales) * 100),2) AS total_txn_penetration<br>FROM product_transactions<br>ORDER BY total_txn_penetration DESC;</pre><p>To allow stakeholders easily generate insights and streamline based on month, weeks or days, all queries were combined into a general scheduled report that the Balanced Tree team can run at the beginning of each month to calculate the previous month’s values.</p><pre>USE balanced_tree;<br><br>SET @start_date = &#39;2021-01-01&#39;;<br>SET @end_date = &#39;2021-01-31&#39;;<br><br><br><br>-- Sales Analysis<br>-- Total quantity sold for all products<br>SELECT SUM(quantity) AS total_qty<br>FROM balanced_tree.sales<br>WHERE start_txn_time BETWEEN @start_date AND @end_date;<br><br>-- Total generated revenue for all products before discounts<br>SELECT SUM(quantity * price) AS total_revenue <br>FROM balanced_tree.sales<br>WHERE start_txn_time BETWEEN @start_date AND @end_date;<br><br>-- Total generated revenue for all products after discounts<br>SELECT SUM((quantity * price) - discount) AS revenue<br>FROM balanced_tree.sales<br>WHERE start_txn_time BETWEEN @start_date AND @end_date;<br><br>-- Total discount amount for all products<br>SELECT SUM(discount) AS total_discount<br>FROM balanced_tree.sales<br>WHERE start_txn_time BETWEEN @start_date AND @end_date;<br><br><br><br>-- Transactions Analysis<br>-- No of unique transactions<br>SELECT COUNT(DISTINCT transaction_id) AS unique_txns<br>FROM balanced_tree.sales<br>WHERE start_txn_time BETWEEN @start_date AND @end_date;<br><br>-- Average unique products purchased in each transaction<br>SELECT ROUND(AVG(unique_products),2) AS average_products_purchased <br>FROM (<br> SELECT transaction_id, <br>    COUNT(DISTINCT product_id) AS unique_products<br> FROM balanced_tree.sales<br>    WHERE start_txn_time BETWEEN @start_date AND @end_date<br> GROUP BY transaction_id<br>) AS unique_products_per_txn;<br><br>-- 25th, 50th and 75th percentile values for the revenue per transaction<br>WITH revenue_per_txn AS (<br>  SELECT transaction_id, <br>      SUM(quantity * price) AS revenue<br>  FROM balanced_tree.sales<br>        WHERE start_txn_time BETWEEN @start_date AND @end_date<br>  GROUP BY transaction_id<br>),<br>ordered_revenues AS (<br>    SELECT revenue,<br>           NTILE(4) OVER (ORDER BY revenue) AS quartile<br>    FROM revenue_per_txn<br>)<br>SELECT<br>    MAX(CASE WHEN quartile = 1 THEN revenue END) AS 25th_percentile,<br>    MAX(CASE WHEN quartile = 2 THEN revenue END) AS 50th_percentile,<br>    MAX(CASE WHEN quartile = 3 THEN revenue END) AS 75th_percentile<br>FROM ordered_revenues;<br><br>-- Average discount value per transaction<br>SELECT ROUND(AVG(total_discount),2) AS average_discount_value<br>FROM (SELECT transaction_id, <br>    SUM(discount) AS total_discount<br>  FROM balanced_tree.sales<br>        WHERE start_txn_time BETWEEN @start_date AND @end_date<br>  GROUP BY transaction_id<br>) AS discount_per_txn;<br><br>-- Percentage split of all transactions for members vs non-members<br>WITH transaction_members AS (<br>  SELECT <br>   DISTINCT(transaction_id),<br>   member_status<br>  FROM balanced_tree.sales<br>        WHERE start_txn_time BETWEEN @start_date AND @end_date<br>)<br>SELECT <br> COUNT(CASE WHEN member_status = 1 THEN 1 END) AS members_txn,<br> COUNT(CASE WHEN member_status = 0 THEN 1 END) AS non_members_txn,<br> (COUNT(CASE WHEN member_status = 1 THEN 1 END) / (SELECT COUNT(DISTINCT transaction_id) FROM balanced_tree.sales WHERE start_txn_time BETWEEN @start_date AND @end_date)) * 100 AS members_prcnt,<br> (COUNT(CASE WHEN member_status = 0 THEN 1 END) / (SELECT COUNT(DISTINCT transaction_id) FROM balanced_tree.sales WHERE start_txn_time BETWEEN @start_date AND @end_date)) * 100 AS non_members_prcnt<br>FROM transaction_members;<br><br>-- Average revenue for member transactions and non-member transactions<br>WITH revenue_per_member AS (<br>  SELECT <br>   DISTINCT(transaction_id),<br>   member_status,<br>   SUM(quantity * price) AS revenue<br>  FROM balanced_tree.sales<br>        WHERE start_txn_time BETWEEN @start_date AND @end_date<br>  GROUP BY transaction_id, member_status<br>)<br>SELECT <br> ROUND(AVG(CASE WHEN member_status = 1 THEN revenue END),2) AS avg_revenue_members,<br> ROUND(AVG(CASE WHEN member_status = 0 THEN revenue END),2) AS avg_revenue_non_members<br>FROM revenue_per_member;<br><br><br><br>-- Product Analysis<br>-- Top 3 products by total revenue before discount&#39;<br>SELECT p.product_name AS product,<br>  SUM(s.quantity * s.price) AS revenue<br>FROM sales s<br>JOIN product_details p<br>  ON p.product_id = s.product_id<br>WHERE start_txn_time BETWEEN @start_date AND @end_date<br>GROUP BY p.product_name<br>ORDER BY revenue DESC<br>LIMIT 3;<br><br>-- Total quantity, revenue and discount for each segment<br>SELECT p.segment_name AS segment,<br>  SUM(quantity) AS total_quantity,<br>        SUM(s.quantity * s.price) AS total_revenue,<br>        SUM(discount) AS total_discount<br>FROM sales s<br>JOIN product_details p<br>  ON p.product_id = s.product_id<br>WHERE start_txn_time BETWEEN @start_date AND @end_date<br>GROUP BY p.segment_name;<br><br>-- Top selling product for each segment<br>WITH ranked_products AS (<br>    SELECT <br>        p.segment_name AS segment,<br>        p.product_name AS product,<br>        SUM(s.quantity) AS total_quantity_sold,<br>        ROW_NUMBER() OVER (PARTITION BY p.segment_name ORDER BY SUM(s.quantity) DESC) AS row_num<br>    FROM sales s<br>    JOIN product_details p <br>    ON p.product_id = s.product_id<br>    WHERE start_txn_time BETWEEN @start_date AND @end_date<br>    GROUP BY p.segment_name, p.product_name<br>)<br>SELECT <br>    segment,<br>    product,<br>    total_quantity_sold<br>FROM ranked_products<br>WHERE row_num = 1;<br><br>-- Total quantity, revenue and discount for each category<br>SELECT p.category_name AS category,<br>  SUM(quantity) AS total_quantity,<br>        SUM(s.quantity * s.price) AS total_revenue,<br>        SUM(discount) AS total_discount<br>FROM sales s<br>JOIN product_details p<br>  ON p.product_id = s.product_id<br>WHERE start_txn_time BETWEEN @start_date AND @end_date<br>GROUP BY p.category_name;<br><br>-- Top selling product for each category<br>WITH ranked_products AS (<br>    SELECT p.category_name AS category,<br>   p.product_name AS product,<br>   SUM(s.quantity) AS total_quantity_sold,<br>   ROW_NUMBER() OVER (PARTITION BY p.category_name ORDER BY SUM(s.quantity) DESC) AS row_num<br>    FROM sales s<br>    JOIN product_details p <br>    ON p.product_id = s.product_id<br> WHERE start_txn_time BETWEEN @start_date AND @end_date<br>    GROUP BY p.category_name, p.product_name<br>)<br>SELECT <br>    category,<br>    product,<br>    total_quantity_sold<br>FROM ranked_products<br>WHERE row_num = 1;<br><br>-- Percentage split of revenue by product for each segment<br>WITH product_revenue AS (<br>    SELECT p.segment_name,<br>   p.product_name,<br>   SUM(s.quantity * s.price) AS revenue,<br>   ROW_NUMBER() OVER (PARTITION BY p.segment_name ORDER BY SUM(s.quantity * s.price) DESC) AS row_num<br>    FROM sales s<br>    JOIN product_details p <br>    ON p.product_id = s.product_id<br> WHERE start_txn_time BETWEEN @start_date AND @end_date<br>    GROUP BY p.segment_name, p.product_name<br>),<br>segment_totals AS (<br>  SELECT segment_name,<br>   SUM(revenue) AS total_revenue<br>  FROM product_revenue<br>  GROUP BY segment_name<br>)<br>SELECT <br>    pr.segment_name,<br>    pr.product_name,<br>    pr.revenue,<br>    ROUND((CASE WHEN pr.row_num &lt;= 3 THEN pr.revenue / st.total_revenue * 100 ELSE 0 END),2) AS percentage_split<br>FROM product_revenue pr<br>JOIN segment_totals st <br>  ON pr.segment_name = st.segment_name;<br><br>-- Percentage split of revenue by segment for each category<br>WITH segment_revenue AS (<br>   SELECT category_name,<br>     segment_name,<br>     SUM(s.quantity * s.price) AS revenue,<br>     ROW_NUMBER() OVER (PARTITION BY p.category_name ORDER BY SUM(s.quantity * s.price) DESC) AS row_num<br>   FROM sales s<br>   JOIN product_details p <br>      ON p.product_id = s.product_id<br>   WHERE start_txn_time BETWEEN @start_date AND @end_date<br>   GROUP BY category_name, segment_name<br>),<br>category_totals AS (<br>  SELECT category_name,<br>    SUM(revenue) AS total_revenue<br>  FROM segment_revenue<br>  GROUP BY category_name<br>)<br>SELECT s.category_name,<br>  s.segment_name,<br>        s.revenue,<br>        ROUND((CASE WHEN row_num &lt;= 2 THEN s.revenue / ct.total_revenue * 100 ELSE 0 END),2) AS percentage_split<br>FROM segment_revenue s<br>JOIN category_totals ct<br>  ON ct.category_name = s.category_name;<br><br>-- Percentage split of total revenue by category<br>WITH category_revenue AS (<br>  SELECT p.category_name,<br>    SUM(s.quantity * s.price) AS revenue<br>  FROM sales s<br>  JOIN product_details p <br>     ON p.product_id = s.product_id<br>  WHERE start_txn_time BETWEEN @start_date AND @end_date<br>  GROUP BY p.category_name<br>)<br>SELECT category_name,<br>  revenue,<br>        ROUND((revenue / (SELECT SUM(quantity * price) FROM balanced_tree.sales WHERE start_txn_time BETWEEN @start_date AND @end_date) * 100),2) AS percentage_split<br>FROM category_revenue;<br><br>-- Total transaction “penetration” for each product<br>WITH product_transactions AS (<br>   SELECT product_name,<br>     COUNT(transaction_id) AS transactions<br>   FROM sales s<br>   JOIN product_details p <br>      ON p.product_id = s.product_id<br>   WHERE start_txn_time BETWEEN @start_date AND @end_date<br>   GROUP BY product_name<br>)<br>SELECT product_name,<br>  transactions,<br>  ROUND((transactions / (SELECT COUNT(DISTINCT transaction_id) FROM balanced_tree.sales WHERE start_txn_time BETWEEN @start_date AND @end_date) * 100),2) AS total_txn_penetration<br>FROM product_transactions<br>ORDER BY total_txn_penetration DESC;<br><br></pre><h3>Data Visualization with Power BI</h3><p>The main purpose of Power BI was to create an interactive visualization to easily communicate the insights and overview to stakeholders and to also verify the results of the exploratory analysis done using MySQL. The dataset was imported into Microsoft Power BI, with initial steps involving data cleaning and transformation to ensure accuracy and consistency.</p><ul><li>Advanced visualizations were made using line charts, bar charts, column charts and tree maps to show the varying trends in revenue, quantity sold and transactions over time.</li><li>Interactive elements were incorporated to allow dynamic exploration of the data, such as filtering by month, day and product.</li></ul><p>The analysis was structured through a main company profile dashboard and three other interactive dashboards; Sales &amp; Revenue dashboard, Products dashboard and Transactions dashboard.</p><ul><li><strong>Sales &amp; Revenue Dashboard: </strong>This dashboard provides a comprehensive overview of the balanced tree clothing company, including quantity sold by day, revenue by gender and month.</li><li><strong>Product Dashboard: </strong>Based on the product analysis; top selling products based on revenue, quantity sold and transactions.</li><li><strong>Transactions Dashboard: </strong>Focuses on the analysis of transactions based on members and non-members status as well as transactions on a daily and monthly basis.</li></ul><p>Below is the resulting visualizations showing the multiple dashboards.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yez2IKFsDN0dWV-TTJlg6g.jpeg" /><figcaption>Balanced Tree Clothing Company Main Profile</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6elCcGZ4ybhIzeprbxn2yA.jpeg" /><figcaption>Sales &amp; Revenue Analysis for Balanced Tree Clothing Company</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6_B8Yzjb2JYz_BbQyG9XTg.jpeg" /><figcaption>Product Analysis for Balanced Tree Clothing Company</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I6ITudaYU3PBD8N6tEC62w.jpeg" /><figcaption>Transactions Analysis for Balanced Tree Clothing Company</figcaption></figure><p><a href="https://app.powerbi.com/view?r=eyJrIjoiZmFhODU2NDMtZTQ2MS00NTAxLWI4MzAtNDI1MzQ5ZjgwODdjIiwidCI6IjEzNzBhYTVmLTZiMTUtNDU1OS1iYzNkLTFjNzE5ZmNmZTVkOSJ9&amp;pageName=b9f2d30a1de2ac092ec2">Power BI Report</a></p><h3>Results and Insights</h3><p>The analysis of the Balanced Tree Clothing Company using Power BI yielded several detailed insights and outcomes, below are the resulting insights.</p><ol><li><strong>Overview of Sales and Revenue</strong></li></ol><p>Balanced Tree Clothing Company has achieved impressive sales and revenue figures within the reported period. The key statistics include:</p><ul><li>Total Revenue: $1,289,453</li><li>Revenue after Discounts: $1,106,753</li><li>Total Discounts Given: $182,700</li><li>Total Quantity Sold: 45,216 items</li><li>Total Unique Transactions: 2,500</li><li>Average Products per Transaction: 6.04 items</li><li>Average Discount per Transaction: $73.08</li></ul><p>These figures indicate a robust sales performance, with significant discounts provided to customers, which likely helped in driving higher sales volumes.</p><p>2. <strong>Revenue and Quantity Sold by Month</strong></p><p>The monthly breakdown of sales quantity is as follows:</p><ul><li>January: 14,788 items sold</li><li>February: 14,820 items sold</li><li>March: 15,608 items sold (Highest)</li></ul><p>Revenue figures per month range between approximately $420K to $450K, showing a consistent sales performance across these months with a slight upward trend.</p><p>3. <strong>Sales and Transactions by Day of the Week</strong></p><p>The analysis of daily sales shows:</p><ul><li>Monday: 7,172 items sold (Highest)</li><li>Tuesday: 6,691 items sold</li><li>Wednesday: 6,618 items sold</li><li>Thursday: 6,586 items sold</li><li>Saturday: 6,261 items sold</li><li>Sunday: 6,015 items sold</li><li>Friday: 5,873 items sold (Lowest)</li></ul><p>The trend indicates that Monday is the most active sales day, while Friday sees the least sales. Similarly, Monday also leads in the number of transactions (397), whereas Friday has the fewest transactions (326).</p><p>4. <strong>Revenue by Gender Category</strong></p><p>Revenue distribution by gender shows:</p><ul><li>Men’s Category: $714,120 (55.38% of total revenue)</li><li>Women’s Category: $575,330 (44.62% of total revenue)</li></ul><p>Men’s clothing accounts for a higher revenue share, suggesting stronger sales performance in this category.</p><p>5. <strong>Revenue by Product Segment</strong></p><p>The breakdown of revenue by product type is as follows:</p><ul><li>Shirts: $406.14K</li><li>Jackets: $366.98K</li><li>Socks: $307.98K</li><li>Jeans: $208.35K</li></ul><p>Shirts are the top revenue-generating product segment, followed by jackets, socks, and jeans.</p><p><strong>6. Top Selling Products by Segment</strong></p><p>The leading products in terms of quantity sold per segment are:</p><ul><li>White Tee — Shirt: 3,876 units (25.54%)</li><li>Grey Fashion — Jacket: 3,707 units (24.43%)</li><li>Navy Solid — Socks: 3,792 units (24.99%)</li><li>Cream Relaxed — Jeans: 3,800 units (25.04%)</li></ul><p>These products have high sales volumes, indicating their popularity among customers.</p><p>7. <strong>Members vs Non-Members Transactions</strong></p><p>The analysis of transactions between members and non-members reveals:</p><ul><li>Members: 1,505 transactions (60.2%)</li><li>Non-Members: 995 transactions (39.8%)</li></ul><p>Members are responsible for a higher proportion of transactions, highlighting the importance of the membership program in driving sales.</p><h3>Recommendations</h3><p><strong>1. Focus on High-Performing Products: </strong>Increase inventory and marketing efforts for top-selling products like Blue Polo Shirts, Grey Fashion Jackets, and White Tee Shirts, which contribute significantly to the revenue.</p><p><strong>2. Enhance Member Engagement: </strong>With members generating 60.2% of transactions, consider expanding loyalty programs to convert more non-members to members. This can be achieved through exclusive member discounts, early access to new products, and personalized marketing.</p><p><strong>3. Boost Weekend Sales: </strong>Since Friday and Sunday are the lowest performing days in terms of sales and transactions, implement targeted promotions or special weekend sales events to drive traffic and sales on these days.</p><p><strong>4. Gender-Specific Marketing: </strong>Given that men’s products account for a larger share of revenue (55.38%), develop targeted marketing campaigns to further capitalize on this segment. However, also explore growth opportunities in the women’s segment to balance the revenue contribution.</p><p><strong>5. Monitor Monthly Sales Trends: </strong>Continue to monitor monthly sales trends and stock inventory accordingly. The increase in sales from January to March indicates a potential upward trend that should be capitalized on.</p><h3>Conclusion</h3><p>The exploratory analysis of Balanced Tree Clothing Company’s sales and revenue data provides a comprehensive understanding of its current performance and areas for potential growth. By implementing the recommendations above, Balanced Tree Clothing Company can optimize its sales performance, enhance customer engagement, and achieve sustained growth. The insights from this analysis provide a solid foundation for strategic decision-making and operational improvements, positioning the company for continued success in the competitive clothing and lifestyle market.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9474b8275d61" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Into the World of a Seafood Store: A Data Exploratory Analysis using SQL & Power BI]]></title>
            <link>https://medium.com/@damoladeagbo/into-the-world-of-a-seafood-store-a-data-exploratory-analysis-using-sql-power-bi-27ceeb5b6ff3?source=rss-ea1964676623------2</link>
            <guid isPermaLink="false">https://medium.com/p/27ceeb5b6ff3</guid>
            <category><![CDATA[clique-bait]]></category>
            <category><![CDATA[marketing]]></category>
            <category><![CDATA[exploratory-data-analysis]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Adedamola A. Adeagbo]]></dc:creator>
            <pubDate>Thu, 04 Jul 2024 21:54:00 GMT</pubDate>
            <atom:updated>2024-07-05T21:54:22.992Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*upTfgFH8lLPvj4i2F_RkqQ.jpeg" /></figure><h3>Introduction</h3><p>Clique bait is an online seafood store that focuses on three major product categories; Shellfish, Luxury and Regular Fish. The store has various users who visit at different times to purchase or view seafood (Crab, Tuna, Lobster, Salmon, Kingfish, etc).</p><p>In this case study, the CEO and Founder Danny, aims to generate insights into the performance of the Clique Bait campaigns, focusing on user engagement, product interactions, and the effectiveness of different promotional campaigns. The data spans from January to May, encompassing metrics such as unique user visits, views, cart additions, events, checkouts, purchases, and campaign impressions.</p><h3>Project Objective</h3><p>The primary objective for this case study is to analyse the provided dataset and come up with creative solutions to calculate funnel fallout rates for the Clique Bait online store. The analysis of this project was grouped into three; Digital, Product Funnel, Campaign Analysis.</p><p>For the Digital analysis, analyse the following:</p><ul><li>How many users are there and many cookies does each user have on average?</li><li>What is the unique number of visits by all users per month?</li><li>What is the number of events for each event type?</li><li>What is the percentage of visits which have a purchase event and the percentage of visits which view the checkout page but do not have a purchase event?</li><li>What are the top 3 pages by number of views?</li><li>What is the number of views and cart adds for each product category</li><li>What are the top 3 products by purchases?</li></ul><p>For the Product Funnel Analysis:</p><ul><li>Which product had the most views, cart adds and purchases?</li><li>Which product was most likely to be abandoned?</li><li>Which product had the highest view to purchase percentage?</li><li>What is the average conversion rate from view to cart add and from cart add to purchase?</li></ul><p>For the Campaign Analysis:</p><ul><li>Identify users who have received impressions during each campaign period and with other users who did not have an impression event.</li><li>Does clicking on an impression lead to higher purchase rates?</li><li>What is the uplift in purchase rate when comparing users who click on a campaign impression versus users who just an impression but do not click?</li></ul><h3>Available Data</h3><p>For this case study there is a total of 5 datasets which you will need to combine to solve all of the questions.</p><ol><li><strong>Users:</strong> Customers who visit the Clique Bait website are tagged via their cookie_id.</li><li><strong>Events:</strong> Customer visits are logged in this events table at a cookie_id level and the event_type and page_id values can be used to join onto relevant satellite tables to obtain further information about each event. The sequence_number is used to order the events within each visit.</li><li><strong>Event Identifier: </strong>The event_identifier table shows the types of events which are captured by Clique Bait’s digital data systems.</li><li><strong>Campaign Identifier:</strong> This table shows information for the 3 campaigns that Clique Bait has ran on their website so far in 2020.</li><li><strong>Page Hierarchy:</strong> This table lists all of the pages on the Clique Bait website which are tagged and have data passing through from user interaction events.</li></ol><h3>Data Importing Process (MySQL)</h3><p>To begin, an automated Extract, Transform, Load (ETL) process needs to be implemented. The ETL process involves, extracting and importing the datasets (All in CSV format) into MySQL where each table will be cleaned; errors and duplicates removed, primary keys and foreign keys will be allocated, uniformity in data types and columns, then after ready to use for analysis.</p><p>The first step in implementing this solution is to create a “clique_bait” schema where each dataset will be added into. After creating the schema, each individual table is created with values inserted into them. Below is the schema and table creation process.</p><pre>CREATE SCHEMA clique_bait;<br><br>USE clique_bait;<br><br>CREATE TABLE clique_bait.event_identifier (<br>  &quot;event_type&quot; INTEGER,<br>  &quot;event_name&quot; VARCHAR(13)<br>);<br><br>CREATE TABLE clique_bait.campaign_identifier (<br>  &quot;campaign_id&quot; INTEGER,<br>  &quot;products&quot; VARCHAR(3),<br>  &quot;campaign_name&quot; VARCHAR(33),<br>  &quot;start_date&quot; TIMESTAMP,<br>  &quot;end_date&quot; TIMESTAMP<br>);<br><br>CREATE TABLE clique_bait.page_hierarchy (<br>  &quot;page_id&quot; INTEGER,<br>  &quot;page_name&quot; VARCHAR(14),<br>  &quot;product_category&quot; VARCHAR(9),<br>  &quot;product_id&quot; INTEGER<br>);<br><br>CREATE TABLE clique_bait.users (<br>  &quot;user_id&quot; INTEGER,<br>  &quot;cookie_id&quot; VARCHAR(6),<br>  &quot;start_date&quot; TIMESTAMP<br>);<br><br>CREATE TABLE clique_bait.events (<br>  &quot;visit_id&quot; VARCHAR(6),<br>  &quot;cookie_id&quot; VARCHAR(6),<br>  &quot;page_id&quot; INTEGER,<br>  &quot;event_type&quot; INTEGER,<br>  &quot;sequence_number&quot; INTEGER,<br>  &quot;event_time&quot; TIMESTAMP<br>);</pre><p>Full importing query with table values:</p><p><a href="https://github.com/Dedamola1/Clique-Bait-Store/blob/24edceb837892c06071028494f71e7d852d12b68/Clique_Bait_Importing.sql">Clique-Bait-Store/Clique_Bait_Importing.sql at 24edceb837892c06071028494f71e7d852d12b68 · Dedamola1/Clique-Bait-Store</a></p><p>After the ETL process, data exploration was carried out on imported data for the digital, product funnel and campaign process.</p><h3>Enterprise Relationship Diagram</h3><p>The enterprise relationship was created to show the relationship between each of the five clique bait datasets. The image below shows a visual representation of what each table is linked on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y9g0z8xCKIIwKk3MknppLQ.jpeg" /></figure><h3>Data Exploratory Process (MySQL)</h3><p>After importing and cleaning, I began to answer each of the required questions for each analysis (Digital, Product Funnel and Campaign Analysis) using single SQL queries.</p><p><strong>Digital Analysis</strong></p><pre>USE clique_bait;<br><br>-- Total Number of Users<br>SELECT COUNT(DISTINCT(user_id)) AS total_users<br>FROM users;<br><br>-- Number of cookies per user on average<br>SELECT ROUND(SUM(total_cookies)/COUNT(users),1) AS average_cookies<br>FROM (SELECT user_id AS users, <br>    COUNT(DISTINCT(cookie_id)) AS total_cookies<br>  FROM users<br>  GROUP BY user_id<br>) AS Agg_table;<br><br>-- Unique number of visits by all Users per month<br>SELECT MONTH(event_time) AS Month_Number, <br>  MONTHNAME(event_time) AS Months, <br>  COUNT(DISTINCT(visit_id)) AS Visits<br>FROM events<br>GROUP BY MONTH(event_time), <br>   MONTHNAME(event_time)<br>ORDER BY MONTH(event_time);<br><br>-- Number of events for each event type<br>SELECT e.event_type,<br>  ei.event_name, <br>  COUNT(*) AS events<br>FROM events e<br>JOIN event_identifier ei<br> ON ei.event_type = e.event_type <br>GROUP BY e.event_type, ei.event_name;<br><br>-- Percentage of visits with a purchase event<br>SELECT ROUND(COUNT(distinct visit_id)*100.0/(SELECT COUNT(distinct visit_id) from events e ) ,2) AS purchase_prcnt<br>FROM events e <br>JOIN event_identifier ei<br>  ON e.event_type = ei.event_type<br>WHERE event_name = &#39;Purchase&#39;;<br>   <br>-- Percentage of visits which view the checkout but do not have a purchase event<br>WITH prct_visits AS (<br>   SELECT DISTINCT(visit_id),<br>   SUM(CASE WHEN event_name!=&#39;Purchase&#39;AND page_id=12 THEN 1 ELSE 0 END) AS checkouts,<br>   SUM(CASE WHEN event_name=&#39;Purchase&#39; THEN 1 ELSE 0 END) AS purchases<br>   FROM events e <br>  JOIN event_identifier ei<br>   ON e.event_type=ei.event_type<br>   GROUP BY visit_id<br>   )<br>   SELECT SUM(checkouts) as total_checkouts,<br>   SUM(purchases) as total_purchases,<br>   100-ROUND(SUM(purchases)*100.0/SUM(checkouts),2) as prcnt<br>   FROM prct_visits;<br><br>-- Top 3 pages by number of views<br>SELECT ph.page_name, <br>  COUNT(visit_id) AS visits<br>FROM page_hierarchy ph<br>JOIN events e <br>  ON e.page_id = ph.page_id<br>GROUP BY ph.page_name<br>ORDER BY visits DESC <br>LIMIT 3;<br><br>-- Number of views and cart adds for each product category<br>SELECT ph.product_category,<br>  COUNT(CASE WHEN e.event_type = 1 THEN 1 END) AS views, <br>  COUNT(CASE WHEN e.event_type = 2 THEN 2 END) AS cart_adds<br>FROM page_hierarchy ph<br>JOIN events e <br>  ON e.page_id = ph.page_id<br>WHERE ph.product_category IS NOT null<br>GROUP BY ph.product_category<br>;<br><br>-- Top 3 products by purchases<br>SELECT ph.page_name, <br>  COUNT(CASE WHEN e.event_type = 2 AND visit_id IN (SELECT DISTINCT visit_id AS purchase_id <br>               FROM events <br>                                                            WHERE event_type = 3 ) <br>     THEN 1 END) AS purchases<br>FROM page_hierarchy ph<br>JOIN events e <br>  ON e.page_id = ph.page_id<br>WHERE ph.product_category IS NOT null<br>GROUP BY ph.page_name<br>ORDER BY purchases DESC<br>LIMIT 3;<br><br><br><br></pre><p><strong>Product Funnel Analysis</strong></p><p>For this analysis, an output table for the product and product category was created which contained the number of times each product was viewed, each product was added to cart, each product was added to a cart but not purchased (abandoned), and times each product was purchased.</p><p>After creating the tables, single SQL queries were written to carry out the funnel analysis.</p><pre>-- Output table for product<br>DROP TABLE IF EXISTS product_tab;<br><br>CREATE TABLE IF NOT EXISTS product_tab (<br>    page_name VARCHAR(50),<br>    page_views INT,<br>    cart_adds INT,<br>    cart_add_not_purchased INT,<br>    purchased INT<br>);<br><br>INSERT INTO product_tab (page_name, page_views, cart_adds, cart_add_not_purchased, purchased)<br>WITH product_CTE AS (<br> SELECT DISTINCT(ph.page_name), <br>   COUNT(CASE WHEN e.event_type = 1 THEN 1 END) AS page_views,<br>   COUNT(CASE WHEN e.event_type = 2 THEN 2 END) AS cart_adds,<br>   COUNT(CASE WHEN e.event_type = 2 AND visit_id NOT IN (SELECT DISTINCT visit_id AS purchase_id <br>                                                          FROM events <br>                                                          WHERE event_type = 3 <br>                                                          AND visit_id IS NOT NULL) <br>              THEN 1 END) AS cart_add_not_purchased,<br>   COUNT(CASE WHEN e.event_type = 2 AND visit_id IN (SELECT DISTINCT visit_id AS purchase_id <br>                                                      FROM events <br>                                                      WHERE event_type = 3 <br>                                                      AND visit_id IS NOT NULL) <br>              THEN 1 END) AS purchased<br> FROM events e<br> JOIN page_hierarchy ph<br>   ON e.page_id = ph.page_id<br> JOIN event_identifier ei <br>   ON e.event_type = ei.event_type <br> WHERE product_category IS NOT null<br> GROUP BY ph.page_name<br>)<br>SELECT page_name, page_views, cart_adds, cart_add_not_purchased, purchased<br>FROM product_CTE;<br><br>SELECT * FROM product_tab;<br><br><br>-- Output table for product category<br>DROP TABLE IF EXISTS product_category_tab;<br><br>CREATE TABLE IF NOT EXISTS product_category_tab (<br>    product_category VARCHAR(50),<br>    page_views INT,<br>    cart_adds INT,<br>    cart_add_not_purchased INT,<br>    purchased INT<br>);<br><br>INSERT INTO product_category_tab (product_category, page_views, cart_adds, cart_add_not_purchased, purchased)<br>WITH product_category_CTE AS (<br> SELECT DISTINCT(ph.product_category), <br>   COUNT(CASE WHEN e.event_type = 1 THEN 1 END) AS page_views,<br>   COUNT(CASE WHEN e.event_type = 2 THEN 2 END) AS cart_adds,<br>   COUNT(CASE WHEN e.event_type = 2 AND visit_id NOT IN (SELECT DISTINCT visit_id AS purchase_id <br>                                                          FROM events <br>                                                          WHERE event_type = 3 <br>                                                          AND visit_id IS NOT NULL) <br>              THEN 1 END) AS cart_add_not_purchased,<br>   COUNT(CASE WHEN e.event_type = 2 AND visit_id IN (SELECT DISTINCT visit_id AS purchase_id <br>                                                      FROM events <br>                                                      WHERE event_type = 3 <br>                                                      AND visit_id IS NOT NULL) <br>              THEN 1 END) AS purchased<br> FROM events e<br> JOIN page_hierarchy ph<br>   ON e.page_id = ph.page_id<br> WHERE product_category IS NOT null<br> GROUP BY ph.product_category<br>)<br>SELECT product_category, page_views, cart_adds, cart_add_not_purchased, purchased<br>FROM product_category_CTE;<br><br>SELECT * FROM product_category_tab;<br><br><br>-- Funnel Analysis<br>-- Product with the most views, cart adds and purchases<br>SELECT page_name AS most_viewed<br>FROM product_tab<br>ORDER BY page_views DESC<br>LIMIT 1;<br><br>SELECT page_name AS most_cart_adds<br>FROM product_tab<br>ORDER BY cart_adds DESC<br>LIMIT 1;<br><br>SELECT page_name AS most_purchases<br>FROM product_tab<br>ORDER BY purchased DESC<br>LIMIT 1;<br><br><br>-- Product most likely to be abandoned<br>SELECT page_name AS most_abandoned<br>FROM product_tab<br>ORDER BY cart_add_not_purchased DESC<br>LIMIT 1;<br><br><br>-- Product with the highest view to purchase percentage<br>SELECT page_name AS product, <br>  ROUND(purchased/page_views * 100,2) AS view_purchase_prcnt<br>FROM product_tab<br>ORDER BY view_purchase_prcnt DESC;<br><br><br>-- Average conversion rate from views to cart_adds<br>SELECT ROUND(AVG(cart_adds/page_views * 100),2) AS avg_conv_rate_views_to_cart<br>FROM product_tab;<br><br><br>-- Average conversion rate from cart_adds to purchases<br>SELECT ROUND(AVG(purchased/cart_adds * 100),2) AS avg_conv_rate_cart_to_purchase<br>FROM product_tab;</pre><p><strong>Campaign Analysis</strong></p><p>For this analysis, an single row output table based on each campaign was created with the following columns;</p><ul><li>User_id,</li><li>Visit_id,</li><li>Visit_start_time: The earliest event_time for each visit,</li><li>Page_views: Count of page views for each visit,</li><li>Cart_adds: Count of product cart add events for each visit,</li><li>Purchases: 1/0 flag if a purchase event exists for each visit,</li><li>Impressions: Count of ad impressions for each visit,</li><li>Clicks: Count of ad clicks for each visit,</li><li>Campaign based on if the visit_start_time falls between the start_date and end_date</li><li>Cart_products: Acomma separated text value with products added to the cart sorted by the order they were added to the cart.</li></ul><p>After creating the tables, single SQL queries were written to carry out the campaign analysis.</p><pre>USE clique_bait;<br><br>-- Output table for campaign<br>DROP TABLE IF EXISTS campaign_tab;<br><br>CREATE TABLE IF NOT EXISTS campaign_tab (<br>user_id INT,<br>visit_id VARCHAR(20),<br>visit_start_time DATETIME(3),<br>page_views INT,<br>cart_adds INT,<br>purchases INT,<br>impressions INT, <br>clicks INT, <br>campaign VARCHAR(200),<br>cart_products VARCHAR(200)<br>);<br><br>INSERT INTO campaign_tab (user_id, visit_id, visit_start_time, page_views, cart_adds, purchases, impressions, clicks, campaign, cart_products)<br>WITH Campaign_CTE AS ( <br> SELECT DISTINCT visit_id, <br>     user_id,<br>                    MIN(e.event_time) as visit_start_time,<br>     COUNT(e.page_id) AS page_views,<br>                    COUNT(CASE WHEN e.event_type = 2 THEN 1 END) AS cart_adds,<br>                    COUNT(CASE WHEN e.event_type = 3 THEN 1 END) AS purchases,<br>                    CASE WHEN MIN(e.event_time) &gt; &#39;2020-01-01 00:00:00&#39; AND MIN(e.event_time) &lt; &#39;2020-01-14 00:00:00&#39; <br>       THEN &#39;BOGOF - Fishing For Compliments&#39;<br>       WHEN MIN(e.event_time) &gt; &#39;2020-01-15 00:00:00&#39; AND MIN(e.event_time) &lt; &#39;2020-01-28 00:00:00&#39;<br>       THEN &#39;25% Off - Living The Lux Life&#39;<br>       WHEN MIN(e.event_time) &gt; &#39;2020-02-01 00:00:00&#39; AND MIN(e.event_time) &lt; &#39;2020-03-31 00:00:00&#39; <br>       THEN &#39;Half Off - Treat Your Shellf(ish)&#39;<br>                    END AS campaign,<br>                    COUNT(CASE WHEN e.event_type = 4 THEN 1 END) AS impressions,<br>                    COUNT(CASE WHEN e.event_type = 5 THEN 1 END) AS clicks,<br>                    GROUP_CONCAT(&#39; &#39;, CASE WHEN product_id IS NOT NULL AND e.event_type = 2<br>            THEN ph.page_name <br>          END) AS cart_products<br> FROM events e <br> JOIN event_identifier ei <br>   ON e.event_type = ei.event_type <br> JOIN users u<br>   ON e.cookie_id = u.cookie_id<br> JOIN page_hierarchy ph<br>   ON e.page_id = ph.page_id<br>    GROUP BY visit_id, user_id         <br>)<br>SELECT user_id, visit_id, visit_start_time, page_views, cart_adds, purchases, impressions, clicks, campaign, cart_products<br>FROM Campaign_CTE;<br><br><br>SELECT *<br>FROM campaign_tab<br>ORDER BY user_id;<br><br>-- Campaign Analysis<br>-- Users who have received impressions during each campaign period vs users without impressions<br>SELECT campaign,<br>  COUNT(DISTINCT CASE WHEN impressions !=0 THEN user_id END) AS users_with_impressions,<br>  COUNT(DISTINCT CASE WHEN user_id NOT IN (SELECT DISTINCT(user_id) AS users<br>          FROM campaign_tab<br>          WHERE impressions != 0 <br>          ORDER BY user_id) THEN user_id END) AS users_without_impressions<br>FROM campaign_tab<br>WHERE campaign IS NOT NULL<br>GROUP BY campaign;<br><br><br>-- Does clicking on an impression lead to higher purchase rates<br>WITH ImpressionPurchaseCTE AS (<br>    SELECT <br>        COUNT(CASE WHEN impressions !=0 THEN 1 END) AS total_impressions,<br>        COUNT(CASE WHEN impressions!=0 AND purchases !=0 THEN 1 END) AS total_purchases_from_impressions<br>    FROM campaign_tab <br>)<br>SELECT total_impressions,<br>  total_purchases_from_impressions,<br>  ROUND((total_purchases_from_impressions * 100.0 / total_impressions),2) AS impression_to_purchase_percentage<br>FROM ImpressionPurchaseCTE;<br><br><br>-- Uplift in purchase rate with users who click on campaign impressions vs users who don&#39;t click <br>WITH Impression_Clicks_PurchaseCTE AS (<br>    SELECT <br>        COUNT(CASE WHEN impressions!=0 AND clicks=1 AND purchases=1 THEN 1 END) AS impressions_from_clicks,<br>        COUNT(CASE WHEN impressions!=0 AND clicks=0 AND purchases=1 THEN 1 END) AS impressions_without_clicks<br>    FROM campaign_tab <br>    WHERE campaign IS NOT NULL<br>)<br>SELECT <br>  impressions_from_clicks,<br>  impressions_without_clicks,<br>  ROUND((impressions_without_clicks * 100.0 / impressions_from_clicks),2) AS uplift_in_purchase_rate<br>FROM Impression_Clicks_PurchaseCTE;</pre><h3>Data Visualization with Power BI</h3><p>The main purpose of Power BI was to create an interactive visualization to easily communicate the insights and overview to stakeholders and to also verify the results of the exploratory analysis done using MySQL. The dataset was imported into Microsoft Power BI, with initial steps involving data cleaning and transformation to ensure accuracy and consistency.</p><p>Before advanced visualizations were done, a calendar table was created to extract the years, months and days from the clique bait dataset. After extracting, the calendar table was linked together with the events table.</p><ul><li>Advanced visualizations were made using line charts, bar charts and column charts to show the varying trends in purchases and views over time.</li><li>Interactive elements were incorporated to allow dynamic exploration of the data, such as filtering by year and country.</li></ul><p>The analysis was structured through an overview dashboard and three interactive dashboards; Digital Analysis, Product Funnel Analysis and Campaign Analysis.</p><ul><li><strong>Digital Analysis Dashboard: </strong>This dashboard provides a comprehensive overview of the clique bait dataset.</li><li><strong>Product Funnel Analysis Dashboard: </strong>Focuses on the analysis of each product and funnel fallout rates for the Clique Bait online store</li><li><strong>Campaign Analysis Dashboard: </strong>Based on the campaigns done by the store, this dashboards shows the performance of the campaigns based on clicks and impressions.</li></ul><p>Below is the resulting visualizations showing the multiple dashboards.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i75lMEMFmglezAOm8TWojg.jpeg" /><figcaption>Clique Bait Store Overview</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KQ0bIurHLzdsXd6ZyyaKCA.jpeg" /><figcaption>Digital Analysis for Clique Bait Store</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XXQcJuV432zftDMhore1mg.jpeg" /><figcaption>Product Funnel Analysis for Clique Bait Store</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eT01QnEwjvoZAyRXmb8YEA.jpeg" /><figcaption>Campaign Analysis for Clique Bait Store</figcaption></figure><p><a href="https://app.powerbi.com/view?r=eyJrIjoiM2Q0Zjg0OGQtZjgxZi00MDQzLWFmZDQtNTU5Yzg4MTFhOTI0IiwidCI6IjEzNzBhYTVmLTZiMTUtNDU1OS1iYzNkLTFjNzE5ZmNmZTVkOSJ9&amp;pageName=2fda6b4b6f52d1726590">Power BI Report</a></p><h3>Results and Insights</h3><p>The analysis of the Clique Bait online store using Power BI yielded several detailed insights and outcomes, below are the resulting insights.</p><p><strong>1. User Engagement: </strong>February saw the highest user engagement with 449 unique users, while May had the lowest with only 16 users.</p><p><strong>Total Engagement Metrics:</strong></p><ul><li>Total Unique Users: 500</li><li>Total Views: 20,928</li><li>Total Cart Adds: 8,451</li><li>Total Purchases: 6,417</li></ul><p><strong>2. Product Category Performance: “</strong>Shellfish” was the most popular category with 6,204 views and 2,898 purchases while “Luxury” was the least popular with 3,032 views and 1,404 purchases.</p><p><strong>3. Top Products:</strong></p><ul><li><strong>Views:</strong> Oyster (1,568 views) was the most viewed product page.</li><li><strong>Cart Adds:</strong> Lobster (968 adds) was the most frequently added to the cart.</li><li><strong>Purchases:</strong> Lobster (754 purchases) was the top purchased product.</li></ul><p><strong>3. Conversion Rates:</strong></p><ul><li><strong>Views to Cart Adds:</strong> Highest conversion was for the Shellfish category.</li><li><strong>Cart Adds to Purchases:</strong> Shellfish also led in converting cart adds to purchases with a 75.93% conversion rate.</li></ul><p><strong>4. Campaign Effectiveness:</strong></p><ul><li><strong>Half Off — Treat Your Shellf(ish): </strong>Most effective campaign with 578 impressions and 493 purchases. Achieved the highest impression to purchase rate at 84.13%.</li><li><strong>BOGOF — Fishing for Compliments: </strong>Least effective with only 59 users receiving impressions and the fewest purchases.</li></ul><p><strong>5. Seasonal Trends: </strong>February had the highest user engagement across most metrics, including impressions from campaign clicks.</p><h3>Recommendations</h3><p><strong>1. Focus on High-Performing Categories:</strong></p><ul><li>Prioritize marketing efforts for the Shellfish category, which consistently shows high engagement and conversion rates.</li><li>Consider expanding the variety within the Shellfish category to further capitalize on its popularity.</li></ul><p><strong>2. Improve Low-Performing Categories:</strong></p><ul><li>Investigate the factors behind the lower performance of the Luxury category.</li><li>Introduce targeted promotions or bundle offers to boost interest and sales.</li></ul><p><strong>3. Optimize Campaign Strategies:</strong></p><ul><li>Replicate the successful elements of the “Half Off — Treat Your Shellf(ish)” campaign in future promotions.</li><li>Conduct A/B testing to refine campaign messaging and offers for the less effective campaigns.</li></ul><p><strong>4. Enhance User Experience:</strong></p><ul><li>Given the high conversion rates, ensure a seamless and user-friendly checkout process to minimize drop-offs.</li><li>Utilize personalized recommendations and reminders for users who add items to the cart but do not complete the purchase.</li></ul><h3>Conclusion</h3><p>The Clique Bait analysis demonstrates that user engagement peaked in February, with Shellfish emerging as the most popular and frequently purchased product category. The “Half Off — Treat Your Shellf(ish)” campaign proved to be the most effective promotional strategy, significantly driving impressions and conversions. By leveraging these insights, Clique Bait can strategically enhance its marketing efforts, focusing on high-performing products and replicating successful campaign elements to boost overall sales and user engagement.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27ceeb5b6ff3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Initial Analysis of a Company’s Sales Data: Observations & Insights]]></title>
            <link>https://medium.com/@damoladeagbo/exploratory-analysis-of-a-companys-sales-data-observations-insights-9524b48ba1d9?source=rss-ea1964676623------2</link>
            <guid isPermaLink="false">https://medium.com/p/9524b48ba1d9</guid>
            <category><![CDATA[sales-analysis]]></category>
            <category><![CDATA[microsoft-power-bi]]></category>
            <category><![CDATA[exploratory-data-analysis]]></category>
            <category><![CDATA[marketing]]></category>
            <dc:creator><![CDATA[Adedamola A. Adeagbo]]></dc:creator>
            <pubDate>Sat, 29 Jun 2024 16:25:07 GMT</pubDate>
            <atom:updated>2024-07-10T18:55:46.336Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wCPh1gvdJtaMrwDDLrrR2A.jpeg" /></figure><h3>Introduction</h3><p>The provided CSV dataset contains detailed sales information for a company, including order-specific data such as order numbers, quantities ordered, price per unit, etc.</p><p>The purpose of the analysis is to leverage all the information provided in the dataset to uncover insights into sales performance trends, identify key revenue drivers, and highlight areas for improvement. By examining sales patterns, geographic location, customer segmentation, and order status, the analysis is a first glance one which just focuses on initial observations and key trends.</p><h3>Initial Observations</h3><p>Based on the initial inspection of the dataset, here are five observations:</p><ul><li><strong>Order Distribution</strong>: The dataset contains details about individual orders, including order numbers, order date, quantities ordered, price per unit, and sales totals.</li><li><strong>Order Status</strong>: The status of each order is recorded (Either Shipped, Cancelled, In-process, On Hold, Disputed or Resolved).</li><li><strong>Geographic Information</strong>: Orders include geographic information such as city, state, postal code, and country, for each customer that purchased a product.</li><li><strong>Customer Details</strong>: The dataset includes customer contact information (names, phone number, address and territories) which can be used for customer segmentation.</li></ul><h3><strong>Results &amp; Insights</strong></h3><p>The Analysis report provides a comprehensive overview of sales performance metrics, highlighting key data points and trends. The analysis, presented through a Power BI Dashboard, offers insights into total orders, revenue, and customer distribution across various regions and product categories.</p><p>Key findings include:</p><ul><li><strong>Total Orders and Customers</strong>: The company processed 2,823 orders from 92 customers.</li><li><strong>Revenue</strong>: Actual revenue reached $8.29 million, falling short of the expected $10 million.</li><li><strong>Top Customers and Revenue Distribution</strong>: The Euro Shopping Channel emerged as the top customer with revenue contributions of $766,195.05, followed by Mini Gifts Distributors Ltd. and Australian Collectors, Co.</li><li><strong>Monthly Trends</strong>: Revenue displayed fluctuations throughout the year, with a notable spike from October to December. November consistently generated the highest monthly revenue.</li><li><strong>Order Status</strong>: 92.7% of orders were shipped, 2.13% were cancelled, and 1.45% remained in process.</li><li><strong>Revenue by Region and Product</strong>: The USA led in revenue generation with $2,986,425.21, and classic cars were the most purchased product category, generating $2,968,546.40.</li></ul><p>Below is a resulting dashboard generated from all the insights gathered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4UnEN4EuhwnIi8o5J09iNQ.jpeg" /><figcaption>Sales Dashboard: Revenue by Contact Name, Total Orders by Month &amp; Customer Name</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q8FO-TSUmuEow6rOpWrjHg.jpeg" /><figcaption>Sales Dashboard: Revenue by Month, Status &amp; Customer Name</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JQj-GZqEuFHI_OR3O1VzkA.jpeg" /><figcaption>Sales Dashboard: Revenue by Year, Country &amp; Product</figcaption></figure><h3>Conclusion</h3><p>Overall, the analysis provides a clear picture of the current sales landscape, highlighting strengths and areas for improvement. By addressing initial data inconsistencies and performing essential data cleaning, the insights derived were both accurate and actionable. These findings provide a foundation for strategic enhancements to boost sales performance and achieve future revenue goals.</p><ul><li><a href="https://hng.tech/internship">HNG Internship | HNG</a></li><li><a href="https://hng.tech/hire">HNG</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9524b48ba1d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tracing Carbon Footprints: A Data Exploration of Global CO2 Emissions Over Time.]]></title>
            <link>https://medium.com/@damoladeagbo/tracing-carbon-footprints-a-data-exploration-of-global-co2-emissions-over-time-3b940bf1046c?source=rss-ea1964676623------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b940bf1046c</guid>
            <category><![CDATA[data-exploration]]></category>
            <category><![CDATA[microsoft-power-bi]]></category>
            <category><![CDATA[carbon-emissions]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Adedamola A. Adeagbo]]></dc:creator>
            <pubDate>Thu, 06 Jun 2024 13:10:33 GMT</pubDate>
            <atom:updated>2024-06-06T19:37:48.143Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zCQoquFFNwL12m9MbTtTWA.jpeg" /></figure><h3>Background</h3><p>Global CO2 emissions, primarily driven by human activities such as the burning of fossil fuels, deforestation, and industrial processes, have significantly increased since the Industrial Revolution. These emissions are a major contributor to the greenhouse effect, leading to global warming and climate change. The effects are profound, including rising sea levels, extreme weather events, and disruptions to ecosystems and biodiversity.</p><p>Currently, the world faces an urgent need to reduce CO2 emissions to mitigate these impacts, with international agreements like the Paris Accord aiming to limit global temperature rise and promote sustainable practices. However, achieving these goals requires coordinated global efforts and substantial changes in energy production, consumption, and policy.</p><h3>Project Objective</h3><p>The primary objective of this project is to conduct a comprehensive exploratory data analysis (EDA) on global CO2 emissions from 1750 to 2021, using a detailed dataset that includes fossil fuel CO2 emissions by country, paired with population data for the same years and countries. This analysis aims to uncover patterns, trends, and insights into the historical and geographical distribution of CO2 emissions, facilitating a better understanding of the dynamics at play over time and across different regions. To conduct this project specific objectives were outlined as follows</p><ul><li><strong>Historical Trends Analysis</strong>: Analysing overall trend of global CO2 emissions from 1750 to 2021, identifying key periods of significant increase or decrease. Also, analysing how global emissions of carbon dioxide (CO2) from fossil fuels and land use changed over time.</li><li><strong>Geographical Distribution</strong>: Identifying the countries with the highest cumulative CO2 emissions over the entire period, highlighting their contributions to global emissions.</li><li><strong>Per Capita Emissions</strong>: Calculating and analysing per capita CO2 emissions for each country and year, discovering where the average person emits the most CO2, and offering insights into the relationship between population growth and emission levels.</li><li><strong>Comparative Analysis</strong>: Comparing CO2 emissions across different continents and economic regions, identifying regional patterns and disparities.</li><li><strong>Visualization and Communication</strong>: Utilising Power BI to create interactive visualizations that effectively communicate key findings and trends to a broad audience.</li></ul><h3>Expected Outcomes</h3><p>This project aims to provide a nuanced understanding of global CO2 emissions, highlighting the interplay between population dynamics, industrialization, and geographical factors. By offering a detailed historical perspective and identifying key contributors to emissions, this analysis seeks to inform policymakers, researchers, and the public, supporting efforts to mitigate climate change and promote sustainable development. The visualizations and insights generated will serve as valuable resources for ongoing discussions and decision-making related to environmental policies and climate action.</p><h3>Exploratory Process</h3><p><strong>Initial Analysis &amp; Data Exploration with Excel</strong></p><p>The dataset provided was a single table dataset with information on global fossil fuel emissions from 1750–2021 by country and region, paired with population and GDP data for the same year/country detail.</p><ul><li>Excel was used to perform initial exploratory analysis in order to understand the dataset values and clean the data. This phase entailed filtering and sorting all the columns, eliminating duplicates, and removing discrepancies such as spelling errors.</li></ul><p><strong>Data Cleaning with Power Query</strong></p><p>ETL process was used to extract and import the dataset (In CSV format) into Power Query where the first row was promoted as a header and the datatype associated with each column was correctly assigned. The dataset had a single table for both countries and region. The first step was separating them using <em>“Duplicate”</em> and <em>“Removing Rows”</em>.</p><blockquote>Duplicate and Remove Rows</blockquote><p>Part of the data cleaning was to separate the regions from the countries. By duplicating the main dataset and renaming the first one as countries then the second dataset as regions. The countries data was filtered to only show the regions, using remove rows function the region rows were deleted. Same step was carried out in the regions data but this time filtering to only show countries and removing the rows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wX6NFkUjC1x-7DywxdRkCA.png" /><figcaption>Removing countries data to create region table</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q-sEkWyavEmksYNYQvo-5g.png" /><figcaption>Removing regions data to create countries table</figcaption></figure><p>After the cleaning was done on Power Query, I selected the “Close &amp; Apply” function to load the data table into Power BI ready for visualization.</p><p><strong>Data Visualization with Power BI</strong></p><p>The dataset was imported into Microsoft Power BI, with initial steps involving data cleaning and transformation to ensure accuracy and consistency. The Power BI visualizations provide a clear and interactive way to understand the dynamics of the railway transport system.</p><p>Before advanced visualizations were done, a calendar table was created to extract the years, months and days from the CO2 dataset. After extracting, the calendar table was linked together with the countries and regions table in the data modelling tab.</p><ul><li>Advanced visualizations were made using line charts, area map chart, bar charts and column charts to show the varying CO2 emissions based on country and over time. This aided in identifying countries with the highest CO2 emissions per country and per capita, also insights into effects of population on these emissions.</li><li>Interactive elements were incorporated to allow dynamic exploration of the data, such as filtering by year and country.</li></ul><p>The analysis was structured through five interactive dashboards: <strong>Overview</strong>, <strong>World Info</strong>, <strong>CO2 Emissions</strong>, <strong>Fossil Fuels Emissions</strong>, and <strong>Other Emissions</strong>.</p><ul><li><strong>Overview and World Info</strong>: This dashboard provides a comprehensive overview of the global dataset. Visuals include a world map displaying total CO2 emissions by country, a bar chart ranking countries by cumulative emissions, world GDP and population growth from 1750 to 2021.</li><li><strong>CO2 Emissions</strong>: Focuses on the analysis of CO2 emissions specifically. Key visuals include a line chart showing the historical trend of CO2 emissions globally and by country, highlighting significant increases or decreases over time.</li><li><strong>Fossil Fuels Emissions</strong>: Dedicated to CO2 emissions from fossil fuels. Contains visuals such as a stacked area chart showing the contribution of different fossil fuels (coal, oil, natural gas) to overall CO2 emissions over time. Also, comparative bar charts highlight the top fossil fuel-emitting countries, enabling users to understand regional dependencies on different fossil fuels.</li><li><strong>Other Emissions</strong>: This dashboard examines other sources of CO2 emissions, including greenhouse emission, and industrial emissions. Visuals include bar charts breaking down the ranking of emissions of various non-fossil fuel sources by country, and a trend chart depicting changes in these emissions over the analysed period.</li></ul><p>Below is the resulting visualization showing the multiple dashboards; overview, world info, CO2 emissions, fossil fuels emissions and other emissions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VvHB-UEWyen88Ud6UDkpIQ.jpeg" /><figcaption>Overview dashboard for global co2 emissions</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DtSzoYIaH56UYo90gAAiwg.jpeg" /><figcaption>Analysis of current world info based on energy, gdp and population</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EHBo2jw273CXUdlm7N_ppw.jpeg" /><figcaption>Insights on co2 emissions trend from 1750 to 2021</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vMdHW2cu12ZynrNFKsA-Xw.jpeg" /><figcaption>Insights on co2 emissions from fossil fuels; Trends and Emissions per Capita</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MRr0xps_JmD5iZsPpB5BNg.jpeg" /><figcaption>Insights on other Emissions; Greenhouse and Industrial Processes</figcaption></figure><p><a href="https://app.powerbi.com/view?r=eyJrIjoiNGU0OTRlYjQtNjA0Ny00ODNmLTg3YjYtYWMxYmFlMGFjMjI4IiwidCI6IjEzNzBhYTVmLTZiMTUtNDU1OS1iYzNkLTFjNzE5ZmNmZTVkOSJ9&amp;pageName=8beec64a40b45e9ae94a">Power BI Report</a></p><h3>Analysis and Insights</h3><p>The analysis of global CO2 emissions using Power BI yielded several detailed insights and outcomes across the four interactive dashboards: World Info, CO2 Emissions, Fossil Fuels Emissions, and Other Emissions.</p><p><strong>Country Contributions</strong>: The world map highlighted that a few countries, primarily the United States, China, and European nations, have been dominant contributors to global emissions. The cumulative emissions bar chart showed the persistent lead of these countries over time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RU2AFW34XzhJp594tDimmQ.jpeg" /></figure><p><strong>Top Emitters</strong>: The line chart showed the United States and China as leading CO2 emitters, with China surpassing the United States in recent decades.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2DXDbLW4wR5vGu7lkZDQJg.jpeg" /></figure><p><strong>Per Capita Emissions</strong>: The line chart revealed that some countries with smaller populations (e.g., Saint Maarten — Dutch Part) have high per capita emissions, while populous countries like United States and United Kingdom have lower per capita emissions despite significant total emissions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p4KFs4uJcktsyRPmcJg5tg.jpeg" /></figure><p><strong>Historical Shifts</strong>: The stacked area chart indicated that coal was the predominant fossil fuel contributing to CO2 emissions historically, with a gradual shift towards oil and natural gas in the mid-20th century.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zzTzCuUMunNJUHpXfN1YFQ.jpeg" /></figure><p><strong>Regional Dependency</strong>: Comparative bar charts showed that different regions rely on various fossil fuels, with some countries predominantly using coal (e.g., China), while others depend more on oil and natural gas (e.g., the United States).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1cwx7vGzCBhtiRiokcSw1A.jpeg" /></figure><p><strong>Non-Fossil Fuel Sources</strong>: Line charts indicated that while fossil fuels are the major source of CO2 emissions, other sources such as Greenhouse gases and industrial processes (e.g., Cement Production) also contribute significantly. The trend chart illustrated changes in emissions from these other sources over time and the bar charts highlighted regions which produce the highest non-fossil fuel emissions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4L4pPtIUJWaPZA2ea2z22Q.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9DrC8Jg-HEplou8IRyW1fw.jpeg" /></figure><h3>Recommendations</h3><p><strong>1. Implement Targeted Emission Reduction Strategies:</strong></p><ul><li><strong>High-Emitting Countries</strong>: Focus on countries like the United States, China, and India, which are leading in total emissions. Tailored strategies should be developed for each country’s specific industrial and energy profiles.</li><li><strong>Per Capita Emissions</strong>: Address the high per capita emissions in smaller yet affluent countries by promoting energy efficiency and cleaner technologies.</li></ul><p><strong>2. Diversify Energy Sources:</strong></p><ul><li><strong>Fossil Fuel Transition</strong>: Encourage a shift from coal to cleaner energy sources like natural gas in regions heavily dependent on coal, such as China and India.</li><li><strong>Renewable Energy Investment</strong>: Increase investments in renewable energy sources, such as wind, solar, and hydroelectric power, to reduce reliance on fossil fuels across all regions.</li></ul><p><strong>3. Strengthen Global and Regional Policies:</strong></p><ul><li><strong>International Cooperation</strong>: Strengthen international agreements like the Paris Accord to ensure collaborative efforts in emission reduction.</li><li><strong>Regional Policies</strong>: Develop policies that address the specific needs and capacities of different regions, recognizing the diverse energy landscapes and economic contexts.</li></ul><p><strong>4. Address Non-Fossil Fuel Emissions:</strong></p><ul><li><strong>Deforestation</strong>: Implement robust measures to curb deforestation and promote reforestation, particularly in regions where land use changes significantly contribute to emissions.</li><li><strong>Industrial Processes</strong>: Encourage cleaner industrial processes and technologies to reduce emissions from non-fossil fuel sources.</li></ul><p><strong>5. Enhance Data Monitoring and Reporting:</strong></p><ul><li><strong>Accurate Tracking</strong>: Improve the accuracy and frequency of emission data collection and reporting to monitor progress and make data-driven decisions.</li><li><strong>Public Transparency</strong>: Promote transparency by making emission data publicly accessible, enabling citizens and stakeholders to track progress and hold governments accountable.</li></ul><p><strong>6. Promote Public Awareness and Education:</strong></p><ul><li><strong>Climate Education</strong>: Increase public awareness and education on the importance of reducing CO2 emissions and adopting sustainable practices.</li><li><strong>Community Engagement</strong>: Engage communities in local and regional emission reduction initiatives, ensuring grassroots participation and support.</li></ul><p>By implementing these recommendations, we can make significant strides in reducing global CO2 emissions, mitigating climate change impacts, and promoting sustainable development worldwide.</p><h3>Conclusion</h3><p>The analysis of global CO2 emissions dataset from 1750 to 2021, conducted using Power BI, has provided a nuanced and comprehensive understanding of global CO2 emissions, revealing critical insights into historical trends, regional disparities, and the multifaceted nature of emission sources. These insights are crucial for informing effective climate action and policy development, emphasizing the need for both global cooperation and targeted regional strategies to mitigate CO2 emissions effectively.</p><p>By focusing on high-emitting countries, promoting renewable energy, and enhancing global cooperation, we can work towards significant reductions in CO2 emissions, contributing to a more sustainable future. The detailed insights and recommendations derived from this analysis serve as a valuable foundation for ongoing climate action and policy development.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b940bf1046c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tracks Uncovered: Using Power BI to Analyse and Visualize the Operations of a UK Rail Network.]]></title>
            <link>https://medium.com/@damoladeagbo/tracks-uncovered-using-power-bi-to-analyse-and-visualize-the-operations-passenger-behaviour-of-a-44e181d1a135?source=rss-ea1964676623------2</link>
            <guid isPermaLink="false">https://medium.com/p/44e181d1a135</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[microsoft-power-bi]]></category>
            <category><![CDATA[national-rail]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[exploratory-data-analysis]]></category>
            <dc:creator><![CDATA[Adedamola A. Adeagbo]]></dc:creator>
            <pubDate>Mon, 27 May 2024 22:19:41 GMT</pubDate>
            <atom:updated>2024-06-06T11:57:13.163Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ekB7KAlWH92NIN2YZRONJA.jpeg" /></figure><h3>Background</h3><p>National Rail Transport, a train service provider based in the United Kingdom. For this project, i played the role of a BI Developer. I was presented with train ticket data for the National Rail transport, from Jan to Apr 2024, including details on the type of ticket, the date &amp; time for each journey, the departure &amp; arrival stations, the ticket price, and more.</p><p>The main aim of this project was developing an exploratory dashboard to evaluate passenger behaviour and operational efficiency. The present study delves into the data analysis conducted on National Rail Transport’s operations, revealing significant insights and trends that could enhance the overall performance of the organization.</p><h3>Project Objective</h3><p>The main objective is to identify key trends, patterns, and insights in the UK National Rail transport system from January to April 2024, using comprehensive ticket sales data. Through the analysis of passenger behaviour and operating performance, National Rail hopes to get insights that support strategic decision-making to enhance operational efficiency, optimize pricing strategies and its operations, and improve customer satisfaction. The following are the main business issues this analysis addresses:</p><ul><li>Identifying the most popular routes (to ensure adequate resources are allocated).</li><li>Determining peak travel times (to manage capacity and reduce congestion).</li><li>Analyzing revenue from different ticket types &amp; classes (to optimize pricing strategies).</li><li>Diagnosing on-time performance and contributing factors (to minimize delays and cancellations).</li></ul><h3>Exploratory Process</h3><p><strong>Initial Analysis &amp; Data Exploration with Excel</strong></p><p>A comprehensive dataset of ticket sales data from January to April 2024 was provided for this challenge, including details on the ticket price, departure &amp; arrival stations, arrival and departure time, passengers preferred ticket class, ticket type, railcard and purchase method.</p><ul><li>Excel was used to perform exploratory data analysis (EDA). In order to find early trends and patterns in the data, this phase entailed filtering and sorting all the columns, eliminating duplicates, and removing discrepancies such as spelling errors. It also involved paying close attention to the frequency and attributes of train routes as well as departure-arrival time.</li></ul><p><strong>Data Cleaning with Power Query</strong></p><p>The majority of the dataset was very clean, since it was just a single table dataset. ETL process was used to extract and import the dataset (In CSV format) into Power Query where the first row was promoted as a header and the datatype associated with each column was correctly assigned. Then I checked for null values and inspected all columns to try and understand the values and attributes assigned to them.</p><p>After the cleaning was done on Power Query, I selected the “Close &amp; Apply” function to load the data table into Power BI ready for visualization.</p><p><strong>Data Visualization with Power BI</strong></p><p>Microsoft Power BI was used to import the Excel dataset that had been cleaned and organized. The Power BI visualizations provide a clear and interactive way to understand the dynamics of the railway transport system.</p><p>Before advanced visualizations were done, a calendar table was created to extract the years, months and days from the main railway dataset. After extracting, the calendar table was linked together with the railway table in the data modelling tab.</p><p>With the aid of Power BI, the following were achieved:</p><ul><li>Advanced visualizations were made using column and bar charts, pie graphs, area charts, and a flow map to show the operating performance and passenger insights. This aided in the identification of high-demand routes and peak travel times, insights into revenue generation by ticket type and class, and an assessment of on-time performance along with its influencing factors.</li><li>Interactive elements were incorporated to allow dynamic exploration of the data, such as filtering by month.</li></ul><p>To present the insights, the following dashboards were created:</p><ul><li><strong>Overview Dashboard</strong>: Highlighting a brief insight into National Rail Transport in the UK with flow map, main departure stations and passenger analysis in view.</li><li><strong>Trips Analysis Dashboard</strong>: This focuses on the top rail routes in the country, most active departure and arrival stations, peak travel periods, on-time, delayed and cancelled trips.</li><li><strong>Revenue Dashboard: </strong>Insights on the revenue per route, highest grossing routes, preferred ticket class and ticket type.</li></ul><p>Below is the resulting visualization showing the multiple dashboards; overview, trips analysis and revenue analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1OB17ex0-OjNS0JMVykCJg.jpeg" /><figcaption>Overview of National Rail Transport</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m-0EQlkAN50S7saQQ87PQg.jpeg" /><figcaption>Insights on Trips &amp; Routes from Departure to Arrival Stations</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NFyj0tDUAnzXJKQPwMS2MA.jpeg" /><figcaption>Insights on Trips &amp; Routes from Departure to Arrival Stations Cont’d</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*senm8ujIsSzUXGcH8oj_dA.jpeg" /><figcaption>Revenue Analysis for Routes, Ticket Class &amp; Ticket Type</figcaption></figure><p><a href="https://app.powerbi.com/view?r=eyJrIjoiYzRjZWM4NTItOGJlZC00N2FjLThjNjAtY2ZhY2RiZjhhNjdkIiwidCI6IjEzNzBhYTVmLTZiMTUtNDU1OS1iYzNkLTFjNzE5ZmNmZTVkOSJ9&amp;pageName=751c576c05c085687605">Power BI Report</a></p><h3>Results &amp; Insights</h3><p>After conducting an exploratory analysis of the National Rail dataset several key insights were uncovered:</p><p><strong>Customer Preference:</strong> Most commuters preferred purchasing their tickets online, with 18,521 tickets purchased compared to at the station which had 13,132 tickets purchased. As with regards to purchasing tickets, 60.46% of commuters preferred using their debit cards.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*9Rilty_inRJKmZx72frplQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*7LBJGK7k4cNnNzoYeFJZ5Q.jpeg" /></figure><p><strong>Routes Analysis:</strong> Based on number of trips, Manchester Piccadilly to Liverpool Lime Street was the most popular route, with a total of 4,338 trips. This also implies that Manchester Piccadilly is the most used departure station, with a total of 5,335 departure trips and was 332.43% higher than Bristol Temple Meads, which had the lowest number of trips at 16 trips.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XDWKyjLAObnXDJGQRoyLdw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r9av--qN8iFKgGkTqFdKRg.jpeg" /></figure><p><strong>Peak Travel Times:</strong> There are <em>two peak travel periods</em> during the day.</p><ul><li><strong>Morning Peak (6 AM — 8 AM)</strong>: With a total of 7,497 trips, this time period sees the most commuters as it suggests most people are traveling to work.</li><li><strong>Evening Peak (4 PM — 6 PM)</strong>: With a total of 7,708 trips, this period has a similar occurrence to the morning peak as it suggest the time commuters are returning home from work.</li><li>Peak periods contributed significantly to revenue, with the morning peak (6 AM to 8 AM) generating £275,397 and the evening peak (4 PM to 6 PM) generating £155,733. The most revenue made in a day was at 8AM, summing up to a total of £132,566.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*N55-nOgJwVCpHklXmjXzvQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*CMU0ImX2uPBedtO13PD9Ig.png" /></figure><p><strong>Revenue based on Routes, Ticket Class &amp; Ticket Type: </strong>A total of 29,773 successful trips occurred during the period, generating total revenue of £703,219.</p><ul><li>The London Kings Cross to York route generated the most revenue, at £179,498, followed distantly by other routes from London.</li><li>Based on the two ticket classes (Standard &amp; First Class), standard tickets generate a total revenue of £560,184, 25.5% more revenue than first class tickets at £143,035. Also, among the ticket types, most commuters purchased Advance tickets for any ticket class.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4vv-vSMdA8W_Y1ikh-A_2Q.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QI_ITejrquilVLZR1igl1g.jpeg" /></figure><p><strong>On-Time Performance &amp; Factors:</strong> From the 31,653 trips booked, a total of 27,481 trips were on time, 92% of all successful journeys (and 86.8% of all bookings). The remaining 4,172 trips were either delayed or cancelled trips. 2,292 trips were delayed and 1,880 trips were cancelled due to various causes.</p><p><strong>Contributing Factors to Delays &amp; Cancellation: </strong>The major reason for delayed trips was “Weather Conditions”, affecting 927 trips out of the total 2,292 delayed trips. From the total 1,880 trips, “Signal Failure” was the major cause of cancelled trips with a total of 519 trips cancelled.</p><ul><li>Due to the delayed and cancelled trips, 1,118 commuters requested for refunds (3.53% of total commuters) resulting in a total of £38,702 refunded. 546 delayed (23.8% of delayed trips) and 572 cancelled (30.4% of cancelled trips) trips were refunded.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4oHXA3kwHx4MZSEkchHUXA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q3vbIMrhivS8Sm8ZT8vdRQ.jpeg" /></figure><h3>Recommendations</h3><ul><li><strong>Allocate Resources to Popular Routes</strong>: Increase train frequency and capacity on the Manchester Piccadilly to Liverpool Lime Street route to accommodate the high passenger demand.</li><li><strong>Optimize Peak Travel Periods</strong>: To manage capacity and enhance the passenger experience, make necessary schedule adjustments and assign more workers during morning and evening peak travel times.</li><li><strong>Revision of Pricing Plans</strong>: In order to balance demand and maximize revenue, examine and modify ticket prices, particularly for the London Kings Cross to York route.</li><li><strong>Improvement on Delayed &amp; Cancelled Trips</strong>: Make infrastructural and technological investments to reduce signal failures and improve communication systems for more effective management of weather-related delays.</li></ul><h3>Conclusion</h3><p>The comprehensive analysis of the UK railway transport data, visualized through Power BI, has unveiled critical insights into the system’s performance and passenger behaviour. Peak travel periods are predominantly during weekday rush hours and weekend afternoons, highlighting key times for resource allocation. Revenue analysis shows a significant contribution from first-class and advance tickets, emphasizing the importance of maintaining premium service levels. Popular routes, especially those connecting major cities like London and Manchester, indicate high demand areas requiring focused operational efficiency.</p><p>On-time performance is commendable at 85%, though efforts to mitigate delays, particularly on long-distance routes and during adverse weather, could further enhance reliability. Passenger preferences lean towards cost-effective advance tickets and convenient travel times, providing a clear directive for marketing and service optimization. Overall, these insights empower the UK National Rail to enhance operational strategies, improve customer satisfaction, and drive future growth.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44e181d1a135" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Visualizing Global Prosperity: Analyzing Key Economic Indicators for Insightful Trends]]></title>
            <link>https://medium.com/@damoladeagbo/visualizing-global-prosperity-analyzing-key-economic-indicators-for-insightful-trends-6821274ed7a6?source=rss-ea1964676623------2</link>
            <guid isPermaLink="false">https://medium.com/p/6821274ed7a6</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[exploratory-data-analysis]]></category>
            <category><![CDATA[excel]]></category>
            <category><![CDATA[power-query]]></category>
            <category><![CDATA[microsoft-power-bi]]></category>
            <dc:creator><![CDATA[Adedamola A. Adeagbo]]></dc:creator>
            <pubDate>Fri, 24 May 2024 17:17:54 GMT</pubDate>
            <atom:updated>2024-05-24T17:17:54.552Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JXT9JY_5D3FxnoWzh3XcTA.jpeg" /></figure><h3>Background</h3><p>The World Bank funds infrastructure projects in the developing world. As part of its mission, it releases an annual report on economic indicators. World Bank has presented a dataset that highlights important indicators of economic performance and development from 1960–2018, including fields like electricity consumption, GDP per capita, life expectancy, birth rate and more.</p><p>To augment the World Bank data, Human Development Index (HDI) data has also been provided by the United Nations (UN). This supplementary dataset contains additional indicators used by the UN to track development, environmental impact, and inequality for each country from 1990–2021.</p><p>With all this data provided, I was able to conduct an in-depth analysis of various economic indicators across different countries and time periods.</p><h3>Project Objective</h3><p>My main objective of this project was to conduct a comprehensive study on each country’s data, focusing on key economic indicators such as GDP growth, population, life expectancy, income, unemployment rates and more.</p><p>I sought to understand how these indicators have changed over time and how they vary by country. I also needed to analyse these economic indicators and identify key trends, and patterns that could inform policy, and investment decisions. Additionally, I aimed to uncover the relationships between different indicators and explore the potential factors driving these relationships.</p><p>For this project, various insights would be generated to understand the world performance of various countries but the recommended analysis involved:</p><ul><li>Identifying which countries have experienced the highest growth in population and GDP? Is there overlap?</li><li>Which regions saw the most growth in HDI in the 21st century?</li><li>Which factors are highly correlated with life expectancy?</li><li>Which factors differentiate “High Income” vs “Low Income” Countries?</li></ul><h3>The Process</h3><h4>Data Exploration with Excel</h4><p>To begin, initial analysis and exploration of the dataset provided by World Bank was done using Excel. This main purpose of using Excel was to find early trends and patterns in the data, this phase entailed:</p><ul><li>Filtering and sorting all the columns in the World Bank dataset and HDI dataset,</li><li>Data cleaning to eliminate duplicates, ensuring all columns are properly categorized and removing discrepancies such as spelling errors.</li></ul><h4><strong>Data Cleaning with Power Query</strong></h4><p>After the data cleaning with Excel, an Extract, Transform and Load (ETL) Process was carried out on the datasets. The ETL process involves, extracting and importing the datasets (All in CSV format) into Power Query where each table will be cleaned and sorted.</p><p><strong>World Bank Dataset</strong></p><p>In the World Bank Data, I began by promoting headers and checking datatypes on the columns in each table. This involved making the first rows as headers to ensure uniformity, change the year column to a date data type. Then I checked for null values and inspected all columns to try and understand the values and attributes assigned to them.</p><blockquote>Replace Values</blockquote><p>Using this function, i renamed values in the income group for High Income. Renaming the values and categorizing them into two new values; Upper High Income and Lower High Income.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z4IQVl8gstfvj61bh0oU_Q.png" /><figcaption>Power Query Transformation on World Bank Table</figcaption></figure><p><strong>HDI Dataset</strong></p><p>The HDI dataset was a very robust data set with 207 rows and 1,008 columns. The dataset contained information on HDI Index and Rankings, Male and Female Life Expectancy, Gender Development and Inequality, Mean and Expected Years of Schooling, Maternal Mortality Rate and more.</p><blockquote>Unpivot Columns</blockquote><p>For this project, i identified columns that were necessary for the analysis and used the unpivot columns function. Using this function I was able to separate each of these columns needed one after the other from the HDI dataset to create individual tables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yN66aS9a9wQ80DZKfC-SNg.png" /><figcaption>Power Query Transformation on HDI Table</figcaption></figure><p>Note that after the unpivot columns, the year data are in alphabet data type. The unpivot command was optimal for being able to group the years and convert the years columns into a date format.</p><p>To convert to date format, the text before the year was removed using the “Extract — Text After Delimiter” function. This function leaves only the date values and you can now convert the data type to a date format easily.</p><h4>Advanced Visualization with Power BI</h4><p>After the cleaning was done on Power Query, I selected the “Close &amp; Apply” function which then loads all the data tables into Power BI ready for visualization.</p><p>Microsoft Power BI was the visualization tool used for this project. The main purpose of Power BI was to create an interactive visualization to easily communicate the insights and overview</p><p>To ensure all the datasets were linked, data modelling was done to link all the tables together using the correct relationship (Country Code). Below is the data cardinality diagram for the dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZSRyzrQ1jJXhwWgWi_BUDA.png" /><figcaption>Data Cardinality for World Economic Indicators</figcaption></figure><p>With the aid of Power BI, the following were achieved:</p><ul><li>Advanced visualizations were made to show the key trends and patterns in the economic indicators. Among these were growth trends in GDP &amp; population, gender comparisons, time-series studies demonstrating the changes in life expectancy, and the correlation income groups and other factors such as region, power consumption, internet usage and more.</li><li>Interactive elements such as “Drill Through”, and “Slicer” were incorporated to allow dynamic exploration of the data, such as filtering by region.</li></ul><p>To present the insights, multiple dashboards were created.</p><ul><li>An Overview Dashboard: Highlighting a brief insight into World Bank with Life Expectancy, GDP &amp; Population, and Income in view.</li><li>GDP &amp; Population Dashboard: Highlighting the top 5 countries with the highest growth in GDP &amp; Population.</li><li>HDI Dashboard: Focusing on HDI growth within the 21st century within Regions as well as showcasing the HDI ranking for countries in 2021.</li><li>Life Expectancy Dashboard: Insights on the average life expectancy for each gender, and other factors such as death and infant mortality rate affecting life expectancy.</li><li>Income Dashboard: Highlighting the various income groups and factors that differentiate low income from middle and high income groups.</li></ul><p>Below is the resulting visualization showing the multiple dashboards; overview, retail and a themes &amp; pieces dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qlexGhZLE3zmbJOhmZMmyA.jpeg" /><figcaption>Overview for World Economic Indicators</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SBe7W3tv-U648C_hL_ZIxQ.jpeg" /><figcaption>Insights on Top 5 Countries with the Highest Growth in GDP &amp; Population</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X4l2ST_ZWtuqqDGVaMdbAw.jpeg" /><figcaption>Analysis of Human Development Index for the 21st Century</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vlQGZL2cN9Ia9VCunFcfQA.jpeg" /><figcaption>Insights on Factors Correlated with Life Expectancy</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yR7VLvLLO9juQ1ONh79RAA.jpeg" /><figcaption>Analysis on Income Group Factors; Low Income, Middle Income, and High Income</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BvWOuef6mHRaA5q80nRnxA.jpeg" /><figcaption>Drill Through Analysis Based on Income Groups</figcaption></figure><p><a href="https://app.powerbi.com/view?r=eyJrIjoiOTg5MmRjMDctMGNlZS00MWQ1LTkxYTMtZWI5NDhhZGM4MzM1IiwidCI6IjEzNzBhYTVmLTZiMTUtNDU1OS1iYzNkLTFjNzE5ZmNmZTVkOSJ9">Power BI Report</a></p><h3>Analysis &amp; Insight</h3><p>After conducting an exploratory analysis of the World Bank dataset several key insights were uncovered:</p><ul><li><strong>GDP &amp; Population Evolution</strong>: The general population density (people per sq. km of land area) had a steady increase over the years, with 2017 being the highest. As for GDP per Capita, there was a rapid increase from 2001 to 2007 with over 89.1% growth. 2014 was the peak point for GDP per capita having a total of $3,573,608.72. Also Europe and Central Asia was the most dominant region, with a total GDP per Capita of $42,015,530.39 and a Population Density of 1,175,142.90. South Asia was the lowest in terms of Population Density and GDP.</li><li><strong>Life Expectancy Trends</strong>: Over the years the average life expectancy has experienced an increase with 2019 having the highest noticeable average life expectancy at 72.4. The average female life expectancy was slightly higher than the male life expectancy, with the male value at 68.59 and female at 71.09.</li><li><strong>Human Development Index: </strong>South Asia had the most growth in HDI in the 21st century with 42.37% growth compared to Sub- Saharan Africa the next region with the highest growth at 34.36%. Based on overall HDI value, North America had the highest rating at 0.90 and Sub-Saharan Africa with the lowest at 0.48. Overall, Switzerland was ranked the number country in terms of HDI.</li><li><strong>Income Groups: </strong>Most countries were found to be in the middle income region, with almost half (101 countries) in this category. Unemployment rate affected most regions, but it had the most effect on Europe &amp; Central Asia with a 10% rate. A large population, 2,865,306 people were under the lower high income group and this group also generated the highest GDP per capita at $34,669,944.42.</li></ul><p>The analysis also showed potential areas for improvement and growth. For example, it highlighted countries that have experienced high growth in population and GDP, presenting potential opportunities for investment.</p><p>Quantifiable results include:</p><ul><li>The average life expectancy grew by 12% from 1960 to 2018.</li><li>GDP per capita increased by approximately 184% globally from 1960 to 2018.</li><li>The Human Development Index saw an average increase of 22% from 1990 to 2021.</li></ul><h3>Conclusion</h3><p>In conclusion, the analysis of key economic indicators from the World Bank dataset offers profound insights into global economic health and development. The correlation between GDP and life expectancy highlights the impact of economic prosperity on quality of life. Population trends, coupled with income data, reveal the disparities and growth patterns across different regions.</p><p>Furthermore, the Human Development Index (HDI) underscores the multifaceted nature of progress, integrating economic performance with social well-being. This comprehensive visualization not only elucidates the current state of global economies but also aids in forecasting future trends and formulating targeted policies for sustainable development.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6821274ed7a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Dive into the LEGO World: Exploratory Analysis on the History & Evolution of LEGO Mini-figures]]></title>
            <link>https://medium.com/@damoladeagbo/a-dive-into-the-lego-world-exploratory-analysis-on-the-history-evolution-of-lego-mini-figures-f6ca0d81129a?source=rss-ea1964676623------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6ca0d81129a</guid>
            <category><![CDATA[microsoft-power-bi]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[analytical-thinking]]></category>
            <category><![CDATA[exploratory-data-analysis]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Adedamola A. Adeagbo]]></dc:creator>
            <pubDate>Tue, 21 May 2024 01:47:45 GMT</pubDate>
            <atom:updated>2024-05-29T15:42:42.128Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6CYeBk_azj1c2sxpIPSajQ.jpeg" /></figure><h3>Background</h3><p>As a young boy, LEGO toys were the foundation for everything, the defining moment where I decided to embark on journey into the world of Engineering and later transitioning into Data Analysis. The goal for each day was to come up with new creative ways to create some otherworldly figure. 20 years later, and that same love for LEGO toys has led me into taking a deep dive into the history, evolution and the essence behind LEGO and LEGO Group.</p><p>The LEGO Group is a privately held company based in Billund, Denmark. The company is still owned by the Kirk Kristiansen family who founded it in 1932.</p><p>As a result of my profound love for LEGO toys, I recently stumbled on a dataset containing LEGO sets released from 1970 to 2022, including details on each set’s theme, categories, pieces, recommended age, retail price, and image. This dataset resulted in me carrying out an exploratory analysis of LEGO mini-figures.</p><h3>Objective</h3><p>This project aimed to explore the history and evolution of LEGO mini-figures, tracing their growth and development over the years from 1970 to 2022. The analysis centred on identifying patterns in the presence of mini-figures and themes in LEGO sets, modifications to design, and the influence of customer preferences and the market on LEGO’s mini-figure strategy.</p><p>For this project various insights were generated regarding the customer and market influence on LEGO mini-figures but the main recommended analysis involved:</p><ul><li>How many LEGO sets have been released since 1970? Is there a noticeable trend?</li><li>Is there a relationship between the price of a set and its number of pieces?</li><li>Which has been the most popular theme in each decade?</li><li>Are LEGO mini-figures most closely tied to licensed sets?</li></ul><h3>The Process</h3><h4>Initial Analysis &amp; Data Exploration with Excel</h4><p>Based on the comprehensive dataset of LEGO sets provided, initial Analysis was done using Microsoft Excel to perform exploratory data analysis (EDA).</p><p>The main aim of using Excel was to find early trends and patterns in the data, this phase entailed:</p><ul><li>Filtering and sorting all the columns in the data set,</li><li>Data cleaning to eliminate duplicates and remove discrepancies,</li><li>Carrying out basic statistical analysis.</li></ul><p>This phase also involved paying close attention to the frequency and attributes of mini-figures in the sets.</p><h4>Advanced Visualization with Power BI</h4><p>Microsoft Power BI was the visualization tool used for this project. The main purpose of Power BI was to create an interactive visualization to easily communicate the insights and overview to stakeholders. Power BI was used to import the Excel dataset that had been cleaned and organized.</p><p>After importing the tables, transformation of the data was carried out using power query to promote headers, and change date type.</p><p>With the aid of Power BI, the following were achieved:</p><ul><li>Advanced visualizations were made to show the development of LEGO mini-figures. Among these were thematic comparisons, time-series studies demonstrating the increase in pieces and mini-figures, and the correlation between LEGO sets and mini-figure inclusion.</li><li>Interactive elements such as “Drill Through”, “Slicer”, and “Tooltips” were incorporated to allow dynamic exploration of the data, such as filtering by decade.</li></ul><p>To present the insights, multiple dashboards were created.</p><ul><li>An Overview Dashboard: Highlighting a brief intro to LEGO’s history and the decades in view</li><li>Retail Dashboard: Showcasing the relationships between LEGO pieces and retail price, average retail price per LEGO set and theme, as well as average retail price per decade.</li><li>Themes &amp; Pieces Dashboard: This focuses on the various set being sold, the top performing themes, amount of mini-figures and pieces.</li></ul><p>Below is the resulting visualization showing the multiple dashboards; overview, retail and a themes &amp; pieces dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iT_3l8sEnJuHPCikkcwipA.jpeg" /><figcaption>Overview for LEGO Group</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qk-66-lFGst6ESB2kfvgzw.jpeg" /><figcaption>Exploratory Analysis based on Relationship between Pieces, Theme and Retail Price</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y3M7TOWUC7tLkFIwFElbRA.jpeg" /><figcaption>Insights based on Sets, Categories, Theme and Pieces</figcaption></figure><h4>Supplementary Internet Research</h4><ul><li>Further online research was done to supplement the data analysis. This research offered background information on significant turning points in the history of LEGO mini-figures, including the launch of the modern mini-figure in 1978, the growth of licensed and themed sets in the 2000s, and current trends toward more varieties and character-driven sets.</li><li>The qualitative analysis gave the story of the LEGO mini-figures a voice and was essential in understanding the data trends.</li></ul><p><a href="https://app.powerbi.com/view?r=eyJrIjoiY2E4ZDgzMDEtYTYzNC00NGRmLTk0MDEtZmE5YjlmMWRlZjc2IiwidCI6IjEzNzBhYTVmLTZiMTUtNDU1OS1iYzNkLTFjNzE5ZmNmZTVkOSJ9">Power BI Report</a></p><h3>Analysis &amp; Insight</h3><p>After conducting an exploratory analysis of the LEGO dataset using Excel and visualizing it with Microsoft Power BI, several key insights were uncovered:</p><ul><li><strong>Growth Trends:</strong> With LEGO’s strategy change toward licensed themes and character-driven sets, there has been a noticeable increase in the number of mini-figures each set, particularly after 2000. Number of usages of LEGO sets was rapidly increased year on year. Year <strong>2022</strong> has the highest total LEGO sets <strong>967</strong> followed by 2021, 2017, and 2020. Year <strong>1974</strong> has lowest total LEGO sets <strong>40</strong> followed by 1972, 1975 and 1970.</li><li><strong>Theme and Pieces Evolution:</strong> The introduction of new themes, particularly licensed franchises, was closely associated with changes in the design and diversity of mini-figures. Themes such as LEGOLAND and Town dominated the earlier decades, while Gear-themed sets gained prominence in the 2000s and beyond. Understanding the popularity of themes in different decades can inform product development decisions, marketing campaigns, and licensing agreements to capitalize on nostalgic appeal and emerging trends.</li><li><strong>Market Influence:</strong> As evidenced by the launch of the Collectible Mini-figures series and the growing diversity of mini-figure representation, consumer preferences and the collector’s market seem to have a big say in LEGO’s mini-figure strategy.</li></ul><p>Further Insights:</p><ul><li>In 2022, the total LEGO Sets produced reached 2,760, marking a 323.3% increase since 1974, the year with the lowest total LEGO sets produced at 652.</li><li>LEGO’s production surged from the mid-20th century.</li><li>LEGO Search Worldwide trended up, with a 385.00% increase between January 1, 2004, and December 1, 2022.</li><li>LEGO expanded its categories from three in 1970 to seven in 2022, with the “Normal” category have highest total of LEGO sets accounting for 69.47% of total LEGO, followed by Gears and Others.</li><li>The top five favoured themes include Gear, Duplo, Star Wars, City, and Collectable Mini-figures.</li><li>The most expensive LEGO sets in five decades are AT-AT and Millennium Falcon, each costing $849.99, followed by Identity and Landscape Kit, Connection Kit, and Imperial Star Destroyer.</li><li>The LEGO set with the most pieces is the Bonus/Value Pack, featuring 38,187 pieces, followed by Taj Mahal with 13,867 pieces.</li></ul><h3>Conclusion</h3><p>The study effectively documented the historical development of LEGO mini-figures, highlighting the ways in which changing consumer tastes, market approaches, and societal factors have influenced the mini-figures history.</p><p>Combining qualitative research with quantitative data analysis allowed for a thorough understanding of the mini-figures evolution from general, simplistic figures to the varied, character-rich components that are essential to the LEGO experience.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6ca0d81129a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Cleaning and Exploratory Analysis of a Global Electronics Retailer using MySQL & Power BI]]></title>
            <link>https://medium.com/@damoladeagbo/data-cleaning-and-exploratory-analysis-of-a-global-electronics-retailer-using-mysql-power-bi-91cb82ab920d?source=rss-ea1964676623------2</link>
            <guid isPermaLink="false">https://medium.com/p/91cb82ab920d</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[exploratory-data-analysis]]></category>
            <category><![CDATA[microsoft-power-bi]]></category>
            <category><![CDATA[data-cleaning]]></category>
            <dc:creator><![CDATA[Adedamola A. Adeagbo]]></dc:creator>
            <pubDate>Wed, 08 May 2024 17:49:05 GMT</pubDate>
            <atom:updated>2024-05-11T23:05:52.779Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PuDsLa64L4UeLXdtFJB6kg.jpeg" /></figure><h3>Data Cleaning and Exploratory Analysis of a Global Electronics Retailer using MySQL &amp; Microsoft Power BI</h3><h3>Background</h3><p>Global Electronics is a local retail store based in the United States that specializes in sales of all electronic products. Their catalogue ranges from the sales of Audio devices, Computers, Home Appliances, Cell Phones, Cameras and Camcorders, Games, Toys, TV and Videos.</p><p>With the rapid growth and expansion of the company, their database of customers and products increases. This has lead to a need for Global Electronics to monitor their marketing performance and make more improved data-driven decisions.</p><p>Due to the current situation, Global Electronics has given us access to their main database which includes tables containing information about transactions, products, customers, stores and currency exchange rates from 2016 to 2021.</p><h3>Task Requirement</h3><p>Stakeholders at Global electronics have presented us with business requirements and insights to be derived from the database to guide their next marketing decisions. The requirements are:</p><ul><li>Overview of customers demographics and stores.</li><li>Top products and the types of products sold.</li><li>Seasonal patterns or trends for order volume and revenue?</li><li>Average delivery time in days and if their are changes over time?</li><li>Average order value (AOV) for online vs. in-store sales, is there any difference?</li><li>Profit, Production Cost and Revenue over time.</li></ul><h3>Data Cleaning Process (MySQL)</h3><p>To begin, an automated Extract, Transform, Load (ETL) process needs to be implemented. ETL allows businesses to consolidate data from multiple databases and other sources into a single repository with data that has been properly formatted and qualified in preparation for analysis.</p><p>The first step in implementing this solution was to extract the data from various sources. Using MySQL Server, I was able to pull data from the different platforms and consolidate it into a single database.</p><p>The ETL process involves, extracting and importing the datasets (All in CSV format) into MySQL where each table will be cleaned; errors and duplicates removed, primary keys and foreign keys will be allocated, uniformity in data types and columns, then after ready to use for analysis.</p><ul><li>Primary Keys: Customer Key on Customers, Product Key on Product, and Store Key on Stores.</li><li>Foreign Keys: On the Transactions Table (Sales); Customer Key, Product Key and Store Key.</li></ul><p>Below is the transformation process of cleaning the dataset after extracting and importing the tables into a Global-Electronics schema created on MySQL.</p><pre>USE global_electronics;<br><br>-- Create Modified Sales Table<br>CREATE TABLE New_Sales_modified<br>LIKE New_sales;<br><br>INSERT new_sales_modified<br>SELECT *<br>FROM new_sales;<br><br>-- Create Modified Products Table<br>CREATE TABLE product_modified<br>LIKE product;<br><br>INSERT product_modified<br>SELECT *<br>FROM product;<br><br>-- Removing Duplicates within Tables<br>WITH Sales_CTE AS<br>(<br>SELECT *,<br>ROW_NUMBER() OVER(PARTITION BY OrderNumber, lineitem, productkey, <br>                  storekey, customerkey) AS Row_Num<br>FROM New_sales_modified<br>)<br>SELECT *<br>FROM Sales_CTE<br>WHERE Row_Num &gt; 1;<br><br>WITH Products_CTE AS<br>(<br>SELECT *,<br>ROW_NUMBER() OVER(PARTITION BY productkey, productname, brand, <br>                  color, subcategorykey, categorykey) AS Row_Num<br>FROM products_modified<br>)<br>SELECT *<br>FROM Products_CTE<br>WHERE Row_Num &gt; 1;<br><br>WITH Customers_CTE AS<br>(<br>SELECT *,<br>ROW_NUMBER() OVER(PARTITION BY customerkey, gender, name, <br>                   city, state, country) AS Row_Num<br>FROM customers<br>)<br>SELECT *<br>FROM customers_CTE<br>WHERE Row_Num &gt; 1;<br><br>-- Updating Date Columns (Customers)<br>SELECT Birthday,<br>STR_TO_DATE(Birthday, &#39;%m/%d/%Y&#39;)<br>FROM Customers;<br><br>UPDATE Customers<br>SET Birthday = STR_TO_DATE(Birthday, &#39;%m/%d/%Y&#39;);<br><br>-- Updating Date Columns (Stores)<br>SELECT OpenDate,<br>STR_TO_DATE(OpenDate, &#39;%m/%d/%Y&#39;)<br>FROM stores;<br><br>UPDATE Stores<br>SET OpenDate = STR_TO_DATE(OpenDate, &#39;%m/%d/%Y&#39;);<br><br>UPDATE stores<br>SET SquareMeters = NULL<br>WHERE SquareMeters = &#39;&#39;;<br><br>-- Updating Date Columns (Exhcange Rates)<br>SELECT `Date`,<br>STR_TO_DATE(`Date`, &#39;%m/%d/%Y&#39;)<br>FROM exchange_rates;<br><br>UPDATE exchange_rates<br>SET `Date` = STR_TO_DATE(`Date`, &#39;%m/%d/%Y&#39;);<br><br>-- Updating Date Columns (New_sales_modified)<br>SELECT OrderDate, STR_TO_DATE(OrderDate, &#39;%m/%d/%Y&#39;),<br>  DeliveryDate, STR_TO_DATE(DeliveryDate, &#39;%m/%d/%Y&#39;)<br>FROM new_sales_modified;<br><br>UPDATE New_sales_modified<br>SET OrderDate = STR_TO_DATE(OrderDate, &#39;%m/%d/%Y&#39;);<br><br>UPDATE New_sales_modified<br>SET DeliveryDate = STR_TO_DATE(DeliveryDate, &#39;%m/%d/%Y&#39;)<br>WHERE DeliveryDate != &#39;&#39;;<br><br>UPDATE New_sales_modified<br>SET DeliveryDate = NULL<br>WHERE DeliveryDate = &#39;&#39;;<br><br>-- Updating Date Columns (New_Sales)<br>SELECT OrderDate, STR_TO_DATE(OrderDate, &#39;%m/%d/%Y&#39;),<br>  DeliveryDate, STR_TO_DATE(DeliveryDate, &#39;%m/%d/%Y&#39;)<br>FROM New_sales;<br><br>UPDATE New_sales<br>SET OrderDate = STR_TO_DATE(OrderDate, &#39;%m/%d/%Y&#39;);<br><br>UPDATE New_Sales<br>SET DeliveryDate = NULL<br>WHERE DeliveryDate = &#39;&#39;;<br><br>UPDATE New_Sales<br>SET DeliveryDate = STR_TO_DATE(DeliveryDate, &#39;%m/%d/%Y&#39;)<br>WHERE DeliveryDate IS NOT NULL;<br><br>-- Recent Exchange Rates<br>CREATE TABLE Recent_Exchange_Rates<br>LIKE exchange_rates;<br><br>INSERT Recent_Exchange_Rates<br>SELECT *<br>FROM exchange_rates<br>WHERE `Date` = &#39;2021-02-20&#39;;<br><br>-- Modifying UnitCost &amp; UnitPrice columns<br>UPDATE product_modified<br>SET unitpriceusd = CAST(REPLACE(unitpriceusd, &#39;$&#39;, &#39;&#39;) AS DECIMAL);<br><br>UPDATE product_modified<br>SET unitcostusd = CAST(REPLACE(unitcostusd, &#39;$&#39;, &#39;&#39;) AS DECIMAL);</pre><p>After the ETL process, data exploratory analysis was carried out on transformed data to generate insights on MySQL before exporting to Microsoft Power BI for visualization.</p><h3>Data Exploratory Process (<strong>MySQL)</strong></h3><p>Using MySQL, I began writing queries to answer each of the business requirements. Each of the queries provide detailed insights into customer demographics, products sold, order volume, profit and revenue from each transaction, store analysis, and average order value.</p><p>The code below shows the full SQL script for the exploratory process and analysis from all the data sources.</p><pre>USE global_electronics;<br><br>-- Types of products sold, and customers location?<br>SELECT DISTINCT  Category, Subcategory, COUNT(category) AS Quantity<br>FROM product_modified<br>GROUP BY Category, Subcategory<br>ORDER BY Category<br>;<br><br>-- Count of Customers by Continent and Country <br>SELECT Continent, Country, <br>  COUNT(Country) AS Count<br>FROM customers<br>GROUP BY Continent, Country<br>;<br><br>-- Seasonal Patterns &amp; Trends for Order Volume and Revenue<br>SELECT Month_Name, <br>        Year_Name,<br>        SUM(QTY) AS Order_Volume, <br>        ROUND(SUM(Revenue),2) AS Total_Revenue_USD<br>FROM<br>   (SELECT monthname(sal.orderdate) AS Month_Name,<br>           year(sal.orderdate) AS Year_Name,<br>           SUM(sal.Quantity) AS QTY, <br>           SUM(sal.Quantity * prod.UnitPriceUSD * Exchange) AS Revenue<br>   FROM new_sales_modified AS sal<br>   LEFT JOIN product_modified AS prod<br>           ON prod.ProductKey = sal.ProductKey<br>   LEFT JOIN recent_exchange_rates AS exc<br>           ON exc.Currency = sal.CurrencyCode<br>   GROUP BY monthname(sal.orderdate), year(sal.orderdate)<br>  ) AS agg_table<br>GROUP BY Year_Name, Month_Name<br>;<br><br>-- Average Delivery Time in Days<br>SELECT AVG(Delivery_Time) AS Avg_Delivery_Time<br>FROM<br>   (SELECT OrderDate, <br>     DeliveryDate, <br>     CAST(datediff(deliverydate, orderdate) AS SIGNED) AS Delivery_Time<br>   FROM new_sales_modified<br>   WHERE DeliveryDate IS NOT NULL<br>   ) AS agg_table2<br>;<br><br>-- Trend of Average Delivery Time by Month and Years<br>WITH Delivery_CTE AS<br>        (SELECT monthname(deliverydate) Delivery_Month, <br>                year(deliverydate) Delivery_Year,<br>                AVG(CAST(datediff(deliverydate, orderdate) AS SIGNED)) <br>                AS Avg_Delivery_Time<br>        FROM new_sales_modified<br>        GROUP BY monthname(deliverydate), <br>                year(deliverydate)<br>        )<br>SELECT *<br>FROM Delivery_CTE<br>WHERE Delivery_Month IS NOT NULL<br>;<br><br>-- Average Order Value for In-Store &amp; Online Sales<br>WITH Store_CTE AS<br>        (SELECT <br>             CASE<br>                  WHEN country = &#39;Online&#39; THEN &#39;Online&#39;<br>                        ELSE &#39;In-store&#39;<br>                   END AS Stores,<br>              SUM(Quantity) AS Order_Volume,<br>              SUM(Quantity * UnitPriceUSD * Exchange) AS Revenue<br>        FROM new_sales_modified AS sal<br>        JOIN stores AS st<br>                ON st.StoreKey = sal.StoreKey<br>        JOIN product_modified AS prod<br>                ON prod.ProductKey = sal.ProductKey <br>         JOIN recent_exchange_rates AS exc<br>                ON exc.Currency = sal.CurrencyCode<br>        GROUP BY CASE<br>                WHEN country = &#39;Online&#39; THEN &#39;Online&#39;<br>                      ELSE &#39;In-store&#39;<br>                 END<br>        )<br>SELECT Stores, ROUND((Revenue/Order_Volume),2) AS Avg_Order_Value<br>FROM Store_CTE<br>;<br>    <br>-- Customers Age Range<br>CREATE VIEW Customers_Age_and_Gender AS<br>SELECT Name, Gender,TIMESTAMPDIFF(YEAR, birthday, CURDATE()) AS Age<br>FROM customers<br>;<br><br>SELECT Gender,<br>        AVG(age) AS Average_Age<br>FROM customers_age_and_gender<br>GROUP BY Gender<br>;<br><br>-- Total Orders &amp; Revenue by Customers<br>SELECT Name,<br>        Country,<br>        SUM(Quantity) AS Total_Orders,<br>        ROUND(SUM(Revenue),2) AS Total_Revenue_USD<br>FROM<br>   (SELECT Name,<br>           Quantity,<br>           Country,<br>           (sal.Quantity * prod.UnitPriceUSD * exc.Exchange) AS Revenue<br>   FROM new_sales_modified AS Sal<br>   JOIN Customers AS Cus<br>          ON Cus.Customerkey = Sal.customerkey<br>   JOIN product_modified AS prod<br>          ON prod.ProductKey = sal.ProductKey <br>   JOIN recent_exchange_rates AS exc<br>          ON exc.Currency = sal.CurrencyCode<br>   ) AS Agg_table5<br>GROUP BY Name, Country<br>ORDER BY Name<br>;<br><br>-- Total Gender Count of Customers<br>SELECT Gender, COUNT(Gender) AS Count<br>FROM customers_age_and_gender<br>GROUP BY Gender<br>;<br><br>-- Total Orders for Online &amp; In-Strore Sales<br>WITH All_Stores_CTE AS<br>        (SELECT <br>             CASE<br>                  WHEN country = &#39;Online&#39; THEN &#39;Online&#39;<br>                        ELSE &#39;In-store&#39;<br>                 END AS Stores,<br>              SUM(Quantity) AS Order_Volume<br>        FROM new_sales_modified AS sal<br>        JOIN stores AS st<br>                ON st.StoreKey = sal.StoreKey<br>        GROUP BY CASE<br>                WHEN country = &#39;Online&#39; THEN &#39;Online&#39;<br>                      ELSE &#39;In-store&#39;<br>               END<br>        )<br>SELECT Stores, Order_Volume AS Total_Order_Volume<br>FROM All_Stores_CTE<br>;<br><br>-- Profit, Revenue, Total Cost, Average Order Value by Products Category<br>WITH Products_CTE AS<br>        (SELECT Quantity, <br>                Category,<br>                (Quantity * UnitPriceUSD *Exchange) AS Revenue,<br>                (Quantity * UnitCostUSD * Exchange) AS Cost<br>        FROM new_sales_modified AS sal<br>        LEFT JOIN product_modified AS prod<br>              ON prod.ProductKey = sal.ProductKey <br>        LEFT JOIN recent_exchange_rates AS exc<br>              ON exc.Currency = sal.CurrencyCode<br>        )<br>SELECT Category AS Product_Category,<br>        SUM(Quantity) AS Total_Order_Vol,<br>        ROUND(SUM(Cost),2) AS Total_Cost_USD, <br>        ROUND(SUM(Revenue),2) AS Total_Revenue_USD,<br>        ROUND(SUM(Revenue - Cost),2) AS Profit_USD,<br>        ROUND(SUM(Revenue)/SUM(Quantity),2) AS Avg_Order_Value<br>FROM Products_CTE<br>GROUP BY Category<br>ORDER BY Category<br>;</pre><h3>Data Visualization Process</h3><p>Microsoft Power BI was the visualization tool used for this project. The main purpose of Power BI was to create an interactive visualization to easily communicate the insights and overview to stakeholders and to also verify the results of the exploratory analysis done using MySQL. To present the insights, two separate dashboards were created.</p><ul><li>Overview Dashboard: Shows the breakdown of customers, demographics and transactions.</li><li>Retail Dashboard: Shows insights into business needs, providing detailed analysis with drill throughs of each requirement.</li></ul><p>After importing the tables, transformation of the data was carried out using power query to promote headers, change date type and remove any discrepancies in the tables.</p><p>Next, the data cardinality diagram below was created linking products, customers, exchange rates and stores to the sales (transactions) table. Also, a calendar table was added to be used as a reference for dates and was also linked to the sales table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VG1lBT2ltE7zBQ7Hm05shQ.png" /><figcaption>Data Cardinality for Global Electronics Database</figcaption></figure><p>Below is the resulting visualization showing the two dashboards; overview and retail analysis, and an informational dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YUBepOG8I8Lyx5NrqwjTZA.jpeg" /><figcaption>Global Electronics Info</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V87BCCmDeRhoHShzKFp_eQ.jpeg" /><figcaption>Global Electronics Overview Dashboard</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M-AB9mGXmlr-MoJqutDkWQ.jpeg" /><figcaption>Global Electronics Analysis Dashboard</figcaption></figure><h3>Analysis &amp; Insight</h3><p>After conducting an exploratory analysis of an electronics retail dataset using MySQL and visualizing it with Microsoft Power BI, several key insights were uncovered:</p><ul><li><strong>Revenue by Product Category</strong>: The analysis revealed that certain product categories outperformed others in terms of sales volume and revenue. Top performing category were the computer sales with $18.6 million in total revenue, this accounted for 34.6% of the total revenue.</li><li><strong>Customer Demographics</strong>: By analyzing customer data such as age, gender, and location, patterns in purchasing behaviour were identified. Most purchases were customers who were residents of United States, having 53.7% of the total orders.</li><li><strong>Seasonal Trends</strong>: Examination of sales data over time highlighted seasonal fluctuations in demand for electronics products. Based on the data presented, 2019 was the best performing year in terms of order volume and revenue. Also, December to February the following year generated the highest revenue and volume across all years, indicating this was a peak purchasing period.</li><li><strong>Geographical Analysis</strong>: Visualizing sales data by region provided insights into geographic areas with the highest demand for electronics products. North America was by far the region with the highest demand for electronics with over 123,000 orders and contributing to 66.7% of the total revenue.</li><li><strong>Store Analysis: </strong>Generally, customers preferred physical stores to online shopping. 79.3% of the revenue was generated from in-store sales while the remainder from online sales.</li></ul><h3>Summary</h3><p>From the exploratory analysis using MySQL and the visualization using Power BI we were able to generate insights and highlight all the key points Global Electronics will need to focus on. The implementation of the automated ETL process significantly improved the efficiency and accuracy of the analysis also reducing data retrieval time by over 35%.</p><p>The results of the visualization correspond with all the queries written and generated using MySQL. This action has led to global electronics making more data-driven decisions enabling them to peak into their customer niche, identify their strengths and weakness, strategizing inventory management and marketing efforts to capitalize on popular categories.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91cb82ab920d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>