<?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 adebola animashaun on Medium]]></title>
        <description><![CDATA[Stories by adebola animashaun on Medium]]></description>
        <link>https://medium.com/@adebolaanimashaun?source=rss-95bf8d798f22------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by adebola animashaun on Medium</title>
            <link>https://medium.com/@adebolaanimashaun?source=rss-95bf8d798f22------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 18:28:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@adebolaanimashaun/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[8 Weeks SQL Challenge by Danny Ma (Case #3): Foodie-Fi Analysis]]></title>
            <link>https://medium.com/@adebolaanimashaun/8-weeks-sql-challenge-by-danny-ma-case-3-foodie-fi-analysis-8f7fe4e1e72d?source=rss-95bf8d798f22------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f7fe4e1e72d</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[adebola animashaun]]></dc:creator>
            <pubDate>Tue, 21 Jan 2025 22:45:42 GMT</pubDate>
            <atom:updated>2025-01-21T22:45:42.615Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome to another interesting case study. This case study stretched me beyond my abilities, and I’m glad I could seek help from my tutor. One of the strengths of a Data Analyst is knowing when to seek help and input from subject matter experts.</p><p>Let’s begin!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Js7ozrel-p2cou5E.png" /></figure><h3>Introduction</h3><p>Subscription-based businesses are super popular, and Danny realized that there was a large gap in the market. He wanted to create a new streaming service that only had food-related content—something like Netflix but with only cooking shows!</p><p>Danny found a few smart friends to launch his new startup Foodie-Fi in 2020 and started selling monthly and annual subscriptions, giving their customers unlimited on-demand access to exclusive food videos from around the world!</p><p>Danny created Foodie-Fi with a data-driven mindset and wanted to ensure all future investment decisions and new features were decided using data. This case study focuses on using subscription-style digital data to answer important business questions.</p><h3>Available Data</h3><p>Danny has shared the data design for Foodie-Fi and also short descriptions of each of the database tables — our case study focuses on only 2 tables but there will be a challenge to create a new table for the Foodie-Fi team.</p><p>All datasets exist within the foodie_fi database schema - be sure to include this reference within your SQL scripts as you start exploring the data and answering the case study questions.</p><p><strong>Entity Relationship Diagram</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/0*LmEpaoY7QcYnjgEd.png" /></figure><p><strong>Solution</strong></p><p><strong>A. Customer Journey</strong></p><p>Based off the 8 sample customers provided in the sample from the subscriptions table, write a brief description of each customer’s onboarding journey.</p><p>Try to keep it as short as possible — you may also want to run some sort of join to make your explanations a bit easier!</p><pre>SELECT s.customer_id, s.plan_id, p.plan_name, s.start_date, p.price<br>FROM subscriptions AS s<br>LEFT JOIN plans AS p<br>ON s.plan_id = p.plan_id<br>WHERE s.customer_id IN (1,2,11,13,15,16,18,19);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*gWYb1Yx3iu7vgnXAWyKq1w.png" /><figcaption>My result.</figcaption></figure><ul><li>Customer-id 1 — First signed up for the 7-day free trial on the 1st of Aug, then upgraded to the basic monthly subscription on the 8th of Aug.</li><li>Customer-id 2 — Signed up first for the 7-day free trial on the 20th of Sept, then upgraded to the pro annual subscription on the 27th of Sept.</li><li>Customer-id 11 — First signed up for the 7-day free trial on the 19th of Nov, didn’t find value in the service, then churned on the 26th of Nov.</li><li>Customer-id 13 — First signed up for the 7-day free trial on the 15th of Dec, then upgraded to the basic monthly subscription on the 22nd of Dec, Liked the service even more, and upgraded to the pro monthly subscription on the 29th of March 2021.</li><li>Customer-id 15 — First signed up for the 7-day free trial on the 17th of March, upgraded to the pro monthly subscription on the 24th of March, then, unfortunately, churned on the 29th of April.</li><li>Customer-id 16 — Signed up first for the 7-day free trial on the 31st of May, then upgraded to the basic monthly subscription on the 7th of June, and upgraded higher to the pro annual subscription on the 21st of Oct.</li><li>Customer-id 18 — First signed up for the 7-day free trial on the 6th of July, then upgraded to the pro monthly subscription on the 13th of July.</li><li>Customer-id 19 — Signed up and went straight to subscribe for the pro monthly plan on the 29th of June, then upgraded to the pro annual subscription on the 29th of Aug.</li></ul><p><strong>B. Data Analysis Questions</strong></p><ol><li>How many customers has Foodie-Fi ever had?</li></ol><p>I used the COUNT function to get the number of customers and DISTINCT to ensure there were no duplicate values.</p><pre>SELECT COUNT(DISTINCT customer_id) AS total_customers<br>FROM subscriptions;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/253/1*ip14EAHwhhHD9ouLfSrLdQ.png" /><figcaption>My result.</figcaption></figure><p>There are a total of 1000 unique customers.</p><p>2. What is the monthly distribution of trial plan start_date values for our dataset — use the start of the month as the group by value.</p><p>I solved this using the MONTHNAME function to help get a monthly breakdown of the trial plan. I also COUNT, INNER_JOIN, GROUP BY, and ORDER BY to achieve this task.</p><pre>SELECT MONTHNAME(s.start_date) AS month_name, COUNT(s.start_date) AS count_per_month<br>FROM subscriptions AS s<br>JOIN plans AS p<br>  ON s.plan_id = p.plan_id<br>WHERE p.plan_name Like &#39;tri%&#39;<br>GROUP BY MONTHNAME(s.start_date)<br>ORDER BY MONTHNAME(s.start_date);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/342/1*SKTBy5_LsFlltPenOV_J-g.png" /><figcaption>My result.</figcaption></figure><p>The above table shows us the monthly breakdown of the trial plan.</p><p>3. What plan start_date values occur after the year 2020 for our dataset. Show the breakdown by count of events for each plan_name.</p><p>For this, I used the COUNT function to get the total number of the plans and WHERE to filter for only plans after 2020/12/31.</p><pre>SELECT p.plan_name, COUNT(p.plan_name) AS breakdown_of_events<br>FROM subscriptions AS s<br>JOIN plans AS p<br>  ON s.plan_id = p.plan_id<br>WHERE s.start_date &gt; &#39;2020-12-31&#39;<br>GROUP BY p.plan_name;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*O2QRUYq10ZRANaKtfx-vRQ.png" /><figcaption>My result.</figcaption></figure><ul><li>Churn category — 71</li><li>Pro-monthly — 60</li><li>Pro-annual — 63</li><li>Basic-monthly — 8</li></ul><p>4. What is the customer count and percentage of customers who have churned rounded to 1 decimal place?</p><p>In this question, I used the CASE WHEN and COUNT functions to count only churned customers. I also used the DISTINCT to get the unique customers, and ROUND to round up my percentage calculation to 1 decimal place.</p><pre>SELECT COUNT(CASE WHEN p.plan_name = &#39;churn&#39; THEN 1<br>  END) AS count_of_churn, <br>  ROUND(COUNT(CASE WHEN p.plan_name = &#39;churn&#39; THEN 1<br>  END) / COUNT(DISTINCT s.customer_id) * 100,1) AS churn_percentage<br>  FROM subscriptions AS s<br>  JOIN plans AS p<br>    ON s.plan_id = p.plan_id;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/1*lEbtolQGxeH2TmrTo05Asw.png" /><figcaption>My result.</figcaption></figure><ul><li>Total churned customers — 307</li><li>Percentage of total customers — 30.7%</li></ul><p>5. How many customers have churned straight after their initial free trial — what percentage is this rounded to the nearest whole number?</p><p>For this, I first used the Window Function (LEAD), to separate the free trial from the other plans, and to make it easier to filter churned customers after the free trial. I also used a CTE to extend my query, and CASE WHEN to pick out the customers that meet the criteria.</p><pre>WITsultH next_plan AS (SELECT customer_id, start_date, plan_id, <br>LEAD(plan_id) OVER (PARTITION BY customer_id) AS next_plan<br>FROM subscriptions)<br>SELECT <br>COUNT(CASE WHEN plan_id = 0 AND next_plan = 4 THEN 1<br>ELSE NULL<br>END) AS count_of_churn, <br>ROUND(COUNT(CASE WHEN plan_id = 0 AND next_plan = 4 THEN 1<br>ELSE NULL<br>END) / COUNT(DISTINCT customer_id) * 100, 0) AS percentage_churn<br>FROM next_plan;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*Rhi7MsRb9oePA448WWz0TA.png" /><figcaption>My result.</figcaption></figure><ul><li>Customers that moved from free trial to churn — 92</li><li>Percentage of total customers — 9%</li></ul><p>6. What is the number and percentage of customer plans after their initial free trial?</p><p>Solving this was a little tedious and lengthy as I used CTE thrice. I also used the FIRST_VALUE window function to filter out the first plan customers started with, then used COUNT to get the total number. I also performed a division and multiplication to get the percentage.</p><pre>WITH first_plan_filter AS (SELECT *,<br>FIRST_VALUE(plan_id) OVER(PARTITION BY customer_id ORDER BY start_date) AS first_plan<br>FROM subscriptions),<br>  <br>plan_filter2 AS (SELECT *<br>FROM first_plan_filter<br>WHERE first_plan = 0<br>AND plan_id &gt; 0),<br>  <br>plan_filter3 AS (SELECT plan_id, COUNT(plan_id) AS plan_count,<br>(SELECT COUNT(plan_id) <br>FROM plan_filter2) AS total_count<br>FROM plan_filter2<br>GROUP BY plan_id)<br><br>SELECT plan_id, plan_count, ROUND((plan_count)/(total_count) * 100, 2) AS percentage<br>FROM plan_filter3;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/1*5cy6jmdiIzVUQpVbWarGWA.png" /><figcaption>My result.</figcaption></figure><ul><li>Basic-monthly plans were 546; 33.09%</li><li>Pro-monthly were 539; 32.67%</li><li>Pro-annual were 258; 15.64%</li><li>Churns were 307; 18.61%</li></ul><p>7. 7. What is the customer count and percentage breakdown of all 5 plan_name values at 2020–12–31?</p><p>Here, I used a COUNT function and a sub-query to create a separate column with the total count of customers without being affected by WHERE I used to filter the date. I also used a CTE to extend my query.</p><pre>WITH customer_number AS (<br>SELECT plan_id, COUNT(customer_id) AS customer_count, <br>(SELECT COUNT(customer_id)<br>FROM subscriptions) AS total_count<br>FROM subscriptions<br>WHERE start_date &lt;=&#39;2020-12-31&#39;<br>GROUP BY plan_id)<br><br>SELECT plan_id, customer_count, ROUND((customer_count)/(total_count) * 100, 2)<br>AS percentage<br>FROM customer_number;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*lSUnsIqGfzJZaEiAwHr0pw.png" /><figcaption>My result.</figcaption></figure><ul><li>The trial plan had 1000 customers; 37.74%</li><li>The basic-monthly plan had 538 customers; 20.30%</li><li>Pro-monthly had 479; 18.08%</li><li>Pro-annual had 195; 7.36%</li><li>Churns were 236; 8.91%</li></ul><p>8. How many customers have upgraded to an annual plan in 2020?</p><p>I used the COUNT function and used WHERE to filter for only 2020.</p><pre>SELECT COUNT(*) AS upgrade_to_annual<br>FROM<br>subscriptions<br>WHERE start_date &lt;= &#39;2020-12-31&#39;<br>AND plan_id = 3;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/236/1*Zxy3XWvNLmJJ9hGBXoeMOQ.png" /><figcaption>My result.</figcaption></figure><ul><li>195 customers upgraded to the annual plan in 2020.</li></ul><p>9. How many days on average does it take for a customer to move to an annual plan from the day they join Foodie-Fi?</p><p>For this question, I relied heavily on Window functions (FIRST_VALUE and LAST_VALUE) to sort the subscriptions table to get the date a customer joined Foodie_Fi, and when they moved to the annual plan.</p><p>I also used the COUNT and DATEDIFF functions and divided them to calculate the average days it took customers to move to the annual plan from their join date.</p><pre>WITH cte AS <br>(SELECT customer_id, <br>FIRST_VALUE(start_date) OVER(PARTITION BY customer_id ORDER BY start_date) <br>AS join_date,<br>LEAD(plan_id) OVER(PARTITION BY customer_id ORDER BY start_date) AS next_plan,<br>LEAD(start_date) OVER(PARTITION BY customer_id ORDER BY start_date) <br>AS next_date<br>FROM subscriptions)<br><br>SELECT ROUND(SUM(DATEDIFF(next_date, join_date)) / <br>COUNT(DATEDIFF(next_date, join_date)), 0) AS annual_upgrade<br>FROM cte<br>WHERE next_plan = 3;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/254/1*CDVM6mjDKI4hE1VzPCVG_w.png" /><figcaption>My result.</figcaption></figure><ul><li>It took 105 days on average to move to the annual plan.</li></ul><p>10. Can you further breakdown this average value into 30-day periods (i.e. 0–30 days, 31–60 days, etc)</p><p>Being a continuation from question 9., I made use of CASE WHEN to categorize into a 30-day interval, the average days it took to move to an annual plan for each customer</p><pre>WITH cte AS <br>(SELECT customer_id, <br>FIRST_VALUE(start_date) <br>OVER(PARTITION BY customer_id ORDER BY start_date) AS join_date,<br>LEAD(plan_id) OVER(PARTITION BY customer_id ORDER BY start_date) AS next_plan,<br>LEAD(start_date) OVER(PARTITION BY customer_id ORDER BY start_date) <br>AS next_date<br>FROM subscriptions)<br><br>SELECT DATEDIFF(next_date, join_date) AS average_days,<br>CASE WHEN DATEDIFF(next_date, join_date) BETWEEN 1 AND 30 THEN &quot;0-30 days&quot;<br> WHEN DATEDIFF(next_date, join_date) BETWEEN 31 AND 60 THEN &quot;31-60 days&quot;<br> WHEN DATEDIFF(next_date, join_date) BETWEEN 61 AND 90 THEN &quot;61-90 days&quot;<br> WHEN DATEDIFF(next_date, join_date) BETWEEN 91 AND 120 THEN &quot;91-120 days&quot;<br> WHEN DATEDIFF(next_date, join_date) BETWEEN 121 AND 150 THEN &quot;121-150 days&quot;<br> WHEN DATEDIFF(next_date, join_date) BETWEEN 151 AND 180 THEN &quot;151-180 days&quot;<br> WHEN DATEDIFF(next_date, join_date) BETWEEN 181 AND 210 THEN &quot;181-210 days&quot;<br> WHEN DATEDIFF(next_date, join_date) BETWEEN 211 AND 240 THEN &quot;211-240 days&quot;<br> WHEN DATEDIFF(next_date, join_date) BETWEEN 241 AND 270 THEN &quot;241-270 days&quot;<br> WHEN DATEDIFF(next_date, join_date) BETWEEN 271 AND 300 THEN &quot;271-300 days&quot;<br> WHEN DATEDIFF(next_date, join_date) BETWEEN 301 AND 330 THEN &quot;301-330 days&quot;<br> WHEN DATEDIFF(next_date, join_date) BETWEEN 331 AND 360 THEN &quot;331-360 days&quot;<br> ELSE &quot;More than 360 days&quot;<br> END AS periods<br>FROM cte<br>WHERE next_plan = 3;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/373/1*COmbEhA8GkM1ZRBPPCe1WQ.png" /><figcaption>My result.</figcaption></figure><ul><li>We can see the breakdown of the average days by customer.</li></ul><p>11. How many customers were downgraded from a pro monthly to a basic monthly plan in 2020?</p><p>I used the LEAD window function to get customers who were downgraded from pro monthly. I also used the COUNT function to get the total number of customers, and finally, used WHERE to filter the date to 2020.</p><pre>WITH downgrade AS (<br>SELECT *,<br>LEAD (plan_id) OVER (PARTITION BY customer_id ORDER BY start_date) <br>AS downgrade<br>FROM subscriptions)<br><br>SELECT COUNT(*) AS no_of_downgrade <br>FROM downgrade<br>WHERE plan_id = 2 AND downgrade = 1<br>AND start_date &lt;= &#39;2020-12-31&#39;;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/203/1*q89ywTBuAiOv9IxTvPMYvQ.png" /><figcaption>My result.</figcaption></figure><ul><li>There were zero number of downgrades.</li></ul><p><em>Thank you!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f7fe4e1e72d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[8 Weeks SQL Challenge by Danny Ma (Case #4): Data Bank]]></title>
            <link>https://medium.com/@adebolaanimashaun/8-weeks-sql-challenge-by-danny-ma-case-4-data-bank-c3488c6e3f0c?source=rss-95bf8d798f22------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3488c6e3f0c</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[adebola animashaun]]></dc:creator>
            <pubDate>Tue, 21 Jan 2025 22:13:30 GMT</pubDate>
            <atom:updated>2025-01-21T22:43:25.172Z</atom:updated>
            <content:encoded><![CDATA[<p>Good to have you again.</p><p>I’m excited to walk you through my thought process and the method I used in handling the Data Bank case study.</p><p>Let&#39;s get started.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*w7rQr_xpXg37bZVJ.png" /></figure><p><strong>Introduction</strong></p><p>There is a new innovation in the financial industry called Neo-Banks: new aged digital-only banks without physical branches.</p><p>Danny thought that there should be some sort of intersection between these new-age banks, cryptocurrency, and the data world…so he decided to launch a new initiative — Data Bank!</p><p>Data Bank runs just like any other digital bank — but it isn’t only for banking activities, they also have the world’s most secure distributed data storage platform!</p><p>Customers are allocated cloud data storage limits directly linked to how much money they have in their accounts. There are a few interesting caveats that go with this business model, and this is where the Data Bank team needs your help!</p><p>The management team at Data Bank wants to increase its total customer base — but also needs some help tracking just how much data storage its customers will need.</p><p>This case study is all about calculating metrics, and growth and helping the business smartly analyze their data to better forecast and plan for their future developments!</p><h4>Available Data</h4><p>The Data Bank team has prepared a data model for this case study as well as a few example rows from the complete dataset below to get you familiar with their tables.</p><h4>Entity Relationship Diagram</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/0*TB8Tb93Y1q-DeXcT.png" /></figure><p><strong>Solution</strong></p><h4>A. Customer Nodes Exploration</h4><ol><li>How many unique nodes are there in the Data Bank system?</li></ol><p>This question was pretty straightforward. I used the COUNT and DISTINCT functions to get the unique nodes.</p><pre>SELECT COUNT(DISTINCT node_id) AS unique_nodes<br>FROM customer_nodes;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/132/1*mT0Me2Y8julMxiqsf5ONYA.png" /><figcaption>My result.</figcaption></figure><ul><li>There are 5 unique nodes.</li></ul><p>2. What is the number of nodes per region? — used inner join cos we are interested in the nodes that are assigned to regions.</p><p>I used INNER JOIN to merge the customer_nodes and regions tables as we are only interested in the nodes that had regions. I went on to use the COUNT function and GROUP BY to get the total nodes by region.</p><pre>SELECT r.region_name, COUNT(c.node_id) AS nodes_per_region<br>FROM customer_nodes AS c<br>JOIN regions AS r<br>  ON c.region_id = r.region_id<br>GROUP BY r.region_name;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*YPdAYmZP5wIb8riq8XhNyw.png" /><figcaption>My result.</figcaption></figure><ul><li>Africa has 714 nodes.</li><li>Europe has 616 nodes.</li><li>Australia has 770 nodes.</li><li>America has 735 nodes.</li><li>Asia has 665 nodes.</li></ul><p>3. How many customers are allocated to each region?</p><p>I used the same logic as before. INNER JOIN, COUNT, and GROUP BY to arrive at my answer. The only different thing here is that I also used DISTINCT because we are interested in unique customers.</p><pre>SELECT r.region_name, COUNT(DISTINCT c.customer_id) AS nodes_per_region<br>FROM customer_nodes AS c<br>JOIN regions AS r<br>  ON c.region_id = r.region_id<br>GROUP BY r.region_name;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*_GJuYMTfQTkxiJxouZQqow.png" /><figcaption>My result.</figcaption></figure><ul><li>Africa has 102 customers.</li><li>America has 105.</li><li>Asia has 95.</li><li>Australia has 110.</li><li>Europe has 88.</li></ul><p>4. How many days on average are customers reallocated to a different node?</p><p>For this, I used the DATEDIFF function to get the difference between the start and end date of a node, which would give us an idea of when a reallocation happens. I also used a COUNT and SUM function and divided to get the average days.</p><p>Note: I noticed some inconsistent dates in the table so I filtered them out using WHERE.</p><pre>WITH reallocation AS (SELECT customer_id, (DATEDIFF( end_date, start_date)) AS reallocation_days<br>FROM customer_nodes<br>WHERE end_date != &#39;9999-12-31&#39;)<br><br>SELECT SUM(reallocation_days)/ COUNT(reallocation_days) AS avg_days<br>FROM reallocation;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/235/1*ky0Kph6yq8FzSHEAaSW99A.png" /><figcaption>My result.</figcaption></figure><ul><li>It took an average of 14.6% days to reallocate a customer to a different node.</li></ul><p>5. What is the median, 80th, and 95th percentile for this same reallocation days metric for each region?</p><p>This question stretched me a lot, but eventually, I pulled through. I had to answer the question In parts.</p><p>First was getting the median, I used the DATEDIFF function to get the reallocation days, then used an NTILE(4) window function to get the median. This was wrapped in a CTE.</p><p>The next was the 80th percentile. For this I used the DATEDIFF function as I did with getting the median, to get the reallocation days, then went ahead to use a PERCENT_RANK() window function to help get the percentile. The data provided was small, so SQL was not able to provide an equal spread, so we had to provide a range using WHERE percentile_rank BETWEEN 79 AND 81, to get the 80th percentile.</p><p>Finally, for the 95th percentile, I just replicated the same procedure I did with the 80th. However, this time I used WHERE percentile_rank BETWEEN 92 AND 95 to triangulate the 95th percentile.</p><pre>-- Median<br><br>WITH reallocation_cte AS (<br>SELECT r.region_name, (DATEDIFF(c.end_date, c.start_date)) AS reallocation_days<br>FROM customer_nodes c<br>JOIN regions r<br>ON c.region_id = r.region_id<br>WHERE c.end_date != &#39;9999-12-31&#39;),<br>ntile_calculation AS (<br>SELECT DISTINCT region_name, reallocation_days,<br>NTILE(4) OVER(PARTITION BY region_name ORDER BY reallocation_days) AS category<br>FROM reallocation_cte)<br>SELECT region_name, MAX(reallocation_days) AS median_time<br>FROM ntile_calculation<br>WHERE category = 2<br>GROUP BY region_name;<br><br>-- 80th percentile<br><br>WITH reallocation_cte AS (<br>SELECT r.region_name, (DATEDIFF(c.end_date, c.start_date)) AS reallocation_days<br>FROM customer_nodes c<br>JOIN regions r<br>ON c.region_id = r.region_id<br>WHERE c.end_date != &#39;9999-12-31&#39;),<br>percent_calc AS (<br>SELECT DISTINCT region_name, reallocation_days,<br>ROUND(PERCENT_RANK() OVER(PARTITION BY region_name ORDER BY reallocation_days) * 100, 0) AS percentile_rank<br>FROM reallocation_cte)<br>SELECT *<br>FROM percent_calc<br>WHERE percentile_rank BETWEEN 79 AND 81;<br><br>-- 95th percentile<br><br>WITH reallocation_cte AS (<br>SELECT r.region_name, (DATEDIFF(c.end_date, c.start_date)) AS reallocation_days<br>FROM customer_nodes c<br>JOIN regions r<br>ON c.region_id = r.region_id<br>WHERE c.end_date != &#39;9999-12-31&#39;),<br>percent_calc AS (<br>SELECT DISTINCT region_name, reallocation_days,<br>ROUND(PERCENT_RANK() OVER(PARTITION BY region_name ORDER BY reallocation_days) * 100, 0) AS percentile_rank<br>FROM reallocation_cte)<br>SELECT *<br>FROM percent_calc<br>WHERE percentile_rank BETWEEN 92 AND 95;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/290/1*d9fKC1SX4Q9EGf5AYdu-dA.png" /><figcaption>Median.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*mvrFgewtPNj_tgc5l-dn9A.png" /><figcaption>80th percentile.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*6rBiavDvRZxaKLlt9J3LxQ.png" /><figcaption>95th percentile.</figcaption></figure><h4>B. Customer Transactions</h4><ol><li>What is the unique count and total amount for each transaction type?</li></ol><p>Here, I used a COUNT, SUM, and a GROUP BY function, to get the count and amount for each transaction type.</p><pre>SELECT txn_type, COUNT(txn_type) AS tnx_type_count, <br>SUM(txn_amount) AS total_amount<br>FROM customer_transactions<br>GROUP BY txn_type;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*Kh92zPh8o1KZKJZXiaisQw.png" /><figcaption>My result.</figcaption></figure><ul><li>We can see the breakdown of the transaction type, the total count of each transaction type, and the total amount by each transaction type.</li></ul><p>2. What is the average total historical deposit counts and amounts for all customers?</p><p>First, I used CASE WHEN to get the deposit count and amount for customers, and then I went ahead and used COUNT and SUM to make my additions. I also made use of the AVERAGE function to arrive at my result, then a GROUP BY function to break down my result by customer. Finally, all of these were wrapped in a CTE to organize my query.</p><pre>WITH deposit_calculation AS (SELECT customer_id, txn_type, <br>COUNT(CASE WHEN txn_type = &#39;deposit&#39; THEN 1 ELSE NULL<br>END) AS deposit_count,<br>SUM(CASE WHEN txn_type = &#39;deposit&#39; THEN txn_amount<br>END) AS total_deposit<br>FROM customer_transactions<br>GROUP BY customer_id, txn_type)<br><br>SELECT txn_type, AVG(deposit_count) AS total_avg_count, AVG(total_deposit) AS total_avg_sum<br>FROM deposit_calculation<br>WHERE txn_type = &#39;deposit&#39;<br>GROUP BY txn_type;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*WJ1nl0OWjepz0QNaMzUH9w.png" /><figcaption>My result.</figcaption></figure><p>3. For each month — how many Data Bank customers make more than 1 deposit and either 1 purchase or 1 withdrawal in a single month?</p><p>This was quite a tricky one, but I could make good of it. I used a CASE WHEN to break down the different transaction types in separate columns, then used SUM to find the total. I ended by using a CTE, GROUP BY, and MONTHNAME function to structure my query and categorize my result by customer and month of the year.</p><pre>WITH txn_type_count AS (<br>SELECT customer_id, MONTHNAME(txn_date) AS txn_months, <br>SUM(CASE WHEN txn_type = &#39;deposit&#39; THEN 1<br>ELSE 0<br>END) AS deposit_criteria,<br>SUM(CASE WHEN txn_type = &#39;purchase&#39; THEN 1<br>ELSE 0<br>END) AS purchase_criteria,<br>SUM(CASE WHEN txn_type = &#39;withdrawal&#39; THEN 1<br>ELSE 0<br>END) AS withdrawal_criteria<br>FROM customer_transactions<br>GROUP BY customer_id, MONTHNAME(txn_date)<br>ORDER BY customer_id)<br><br>SELECT txn_months, COUNT(DISTINCT customer_id) AS customer_count<br>FROM txn_type_count<br>WHERE (deposit_criteria &gt; 1) AND (purchase_criteria = 1 OR withdrawal_criteria = 1)<br>GROUP BY txn_months;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*Gu7uD7bDonEoHRHDKAmjCg.png" /><figcaption>My result.</figcaption></figure><ul><li>For April, the customer count was 50.</li><li>For February, 108.</li><li>For January, 115.</li><li>and March, 113.</li></ul><p>4. What is the closing balance for each customer at the end of the month?</p><p>Similar to my approach to the previous question, I used a CTE to structure my query, and CASE WHEN to break down each transaction type, and then MONTHNAME to break the dates by month. I also used GROUP BY and ORDER BY to categorize and sort the closing balance by customer.</p><p>Finally, I used the SUM function to get the total closing balance at the end of each month.</p><pre>WITH transaction_types AS (SELECT customer_id,  MONTHNAME(txn_date) AS txn_months,<br>SUM(CASE WHEN txn_type = &#39;deposit&#39; THEN txn_amount<br>ELSE 0<br>END) AS monthly_deposit,<br>SUM(CASE WHEN txn_type = &#39;withdrawal&#39; THEN txn_amount<br>ELSE 0<br>END) AS monthly_withdrawal,<br>SUM(CASE WHEN txn_type = &#39;purchase&#39; THEN txn_amount<br>ELSE 0<br>END) AS monthly_purchase<br>FROM customer_transactions<br>GROUP BY customer_id, txn_months<br>ORDER BY customer_id)<br><br>SELECT customer_id, txn_months, SUM(monthly_deposit) - SUM(monthly_withdrawal + monthly_purchase) AS closing_balance<br>FROM transaction_types<br>GROUP BY customer_id, txn_months; </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*lR4UwrA_3xOE8i1Pior8Wg.png" /><figcaption>My result.</figcaption></figure><ul><li>Customers reflected multiple times because they carried out transactions and had closing balances in different months.</li></ul><p>5. What is the percentage of customers who increase their closing balance by more than 5%?</p><p>This was an interesting question. I began by using the FIRST_VALUE window function to get each customer&#39;s opening balance. I used CASE WHEN to break the different transaction types into separate columns to do my calculations.</p><p>I finally went ahead to calculate the closing balance and also got the percentage of customers who had a closing balance above 5%. All of these queries were linked using a CTE.</p><pre>WITH opening_balance AS <br>(SELECT customer_id, txn_type, txn_amount, FIRST_VALUE(txn_amount) <br>OVER(PARTITION BY customer_id ORDER BY txn_date) AS opening_balance<br>FROM customer_transactions),<br><br>closing_balance AS (SELECT customer_id, opening_balance,<br>SUM(CASE WHEN txn_type = &#39;deposit&#39; THEN txn_amount<br>ELSE 0<br>END) AS monthly_deposit,<br>SUM(CASE WHEN txn_type = &#39;withdrawal&#39; THEN txn_amount<br>ELSE 0<br>END) AS monthly_withdrawal,<br>SUM(CASE WHEN txn_type = &#39;purchase&#39; THEN txn_amount<br>ELSE 0<br>END) AS monthly_purchase<br>FROM opening_balance<br>GROUP BY customer_id, opening_balance),<br><br>percentage_calculation AS <br>(SELECT customer_id, opening_balance, monthly_deposit - <br>(monthly_withdrawal + monthly_purchase) AS closing_balance,<br>ROUND((((monthly_deposit - (monthly_withdrawal + monthly_purchase)) - <br>opening_balance) / opening_balance) * 100, 0) AS percentage_calc<br>FROM closing_balance<br>ORDER BY customer_id)<br><br>SELECT ROUND(COUNT(customer_id)/ <br>(SELECT COUNT(customer_id) FROM percentage_calculation) * 100, 0) <br>AS percentage_of_customers_with_increase<br>FROM percentage_calculation<br>WHERE percentage_calc &gt; 5;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/1*LhKzrg2Zb5GTaVgt1C416Q.png" /><figcaption>My result.</figcaption></figure><ul><li>33% of customer increased their closing balance by 5%.</li></ul><p><em>Thank you for sticking with me. Cheers!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3488c6e3f0c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[8 Week SQL Challenge: Case Study #2: Pizza Runner]]></title>
            <link>https://medium.com/@adebolaanimashaun/8-week-sql-challenge-case-study-2-pizza-runner-2e3475d926d7?source=rss-95bf8d798f22------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e3475d926d7</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[adebola animashaun]]></dc:creator>
            <pubDate>Sun, 19 Jan 2025 19:38:40 GMT</pubDate>
            <atom:updated>2025-01-19T19:38:40.057Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome back,</p><p>This time, I’ll explain how I tackled the Pizza Runner case study. Do enjoy! If you missed my first case study and would like to take a look, here’s a <a href="https://medium.com/@adebolaanimashaun/f48460f4a3b0">link.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wE2l4pT3mlrskwhd.png" /></figure><h4>Introduction</h4><p>Did you know that over <strong>115 million kilograms</strong> of pizza are consumed daily worldwide? (According to Wikipedia, anyway…)</p><p>Danny was scrolling through his Instagram feed when something caught his eye — “80s Retro Styling and Pizza Is The Future!”</p><p>Danny was sold on the idea, but he knew that pizza alone was not going to help him get seed funding to expand his new Pizza Empire — so he had one more genius idea to combine with it — he was going to <em>Uberize</em> it — and so Pizza Runner was launched!</p><p>Danny started by recruiting “runners” to deliver fresh pizza from Pizza Runner Headquarters (otherwise known as Danny’s house) and also maxed out his credit card to pay freelance developers to build a mobile app to accept orders from customers.</p><h4>Available Data</h4><p>Because Danny had a few years of experience as a data scientist — he was very aware that data collection was going to be critical for his business’ growth.</p><p>He has prepared for us an entity relationship diagram of his database design but requires further assistance to clean his data and apply some basic calculations so he can better direct his runners and optimize Pizza Runner’s operations.</p><p>All datasets exist within the pizza_runner database schema - be sure to include this reference within your SQL scripts as you start exploring the data and answering the case study questions.</p><h4>Case Study Questions</h4><p>This case study has <strong>LOTS</strong> of questions — they are broken up by area of focus including:</p><ul><li>Pizza Metrics</li><li>Runner and Customer Experience</li><li>Ingredient Optimisation</li><li>Pricing and Ratings</li><li>Bonus DML Challenges (DML = Data Manipulation Language)</li></ul><p>Before you start writing your SQL queries, however — you might want to investigate the data, you may want to do something with some of those null values and data types in the customer_orders and runner_orders tables!</p><p>The entity relationship diagram has been given to us below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hvbbZmunukywC1TL.png" /></figure><p>Let’s get started, shall we?</p><h4>Data Cleaning and Transformation</h4><p>Before I delve into answering questions, Let’s take some time to clean up the data presented, so it&#39;s usable.</p><p><em>Cleaning the customer_orders table</em></p><p>A close look at the table below shows some irregularities in the ‘exclusions’ and ‘extras’ columns, where we have some blank rows, as well as some others with ‘null’ string values</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/0*5VqfwT7j-o9WZwlo.png" /></figure><p><em>Let&#39;s turn the blank fields, and rows with ‘null’ string values to NULL values in the ‘exclusions’ and ‘extras’ columns.</em></p><pre><br>UPDATE customer_orders<br>SET exclusions = null<br>WHERE exclusions = &#39;&#39;<br>AND exclusions = &#39;null&#39;;<br><br>UPDATE customer_orders<br>SET extras = null<br>WHERE extras = &#39;&#39;<br>AND extras = &#39;null&#39;;</pre><p>Let’s check the updated table;</p><pre>SELECT * <br>FROM customer_orders;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/0*zgHsr6PWLQLUaPXg.png" /></figure><p>Looks good now.</p><p><em>Cleaning the runner_orders table</em></p><p>The table below has quite several issues to be fixed. There are ‘null’ string values and blank fields in the pick-up, distance, duration, and cancellation columns. From the entity relationship diagram, we see that there’s a need to change the datatypes of these columns to make the data usable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3W01JALe-2paOlP2.png" /></figure><p><em>Let&#39;s change the ‘null’ and blanks to NULL in the pick-up, distance, duration, and cancellation columns.</em></p><pre><br>UPDATE runner_orders<br>SET pickup_time = null<br>WHERE pickup_time = &#39;null&#39;;<br><br>UPDATE runner_orders<br>SET distance = null<br>WHERE distance = &#39;null&#39;;<br><br>UPDATE runner_orders<br>SET duration = null<br>WHERE duration = &#39;null&#39;;<br><br>UPDATE runner_orders<br>SET cancellation = null<br>WHERE cancellation = &#39;&#39;<br>OR cancellation = &#39;null&#39;;</pre><p><em>Changing pick-up time column datatype to TIMESTAMP</em></p><pre>ALTER TABLE runner_orders<br>MODIFY pickup_time TIMESTAMP;</pre><p><em>Changing distance column datatype to INTEGER</em></p><pre>UPDATE runner_orders<br>SET distance = TRIM(REPLACE(distance, &#39;km&#39;, &#39; &#39;));<br><br>ALTER TABLE runner_orders<br>MODIFY distance DOUBLE;</pre><p><em>Changing duration column datatype to INTEGER</em></p><pre>UPDATE runner_orders<br>SET duration = SUBSTRING(duration,1,2);<br><br>UPDATE runner_orders<br>SET duration = 10<br>WHERE order_id = 10;<br><br>ALTER TABLE runner_orders<br>MODIFY duration INT;</pre><p>Let’s take a look at our cleaned table.</p><pre>SELECT *<br>FROM runner_orders;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/0*3L5iaQxbLSnsBh2d.png" /></figure><p>Looks good. Now let’s answer some questions.</p><p><strong>Answers to questions</strong></p><h4><strong>Section A. Pizza metrics</strong></h4><ol><li>How many pizzas were ordered?</li></ol><p>I used the COUNT aggregate function here to get the total number of pizzas ordered.</p><pre>SELECT COUNT(order_id) AS total_pizzas_bought<br>FROM customer_orders:</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/373/1*H7St1h97doazupPc-YmpFg.png" /><figcaption>My result.</figcaption></figure><ul><li>A total of 14 pizzas were ordered.</li></ul><p>2. How many unique customer orders were made?</p><p>I used the COUNT function and DISTINCT, to calculate get the total unique numbers of customer orders that were made.</p><pre>SELECT COUNT(DISTINCT order_id) AS unique_customer_orders<br>FROM customer_orders;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/329/1*XAph4N3W4okw9HuZcI_ncg.png" /><figcaption>My result.</figcaption></figure><ul><li>Ten distinct orders were placed.</li></ul><p>3. How many successful orders were delivered by each runner?</p><p>Here, I joined the runner_orders and customer_orders tables and then used the COUNT function to get the deliveries by runners.</p><pre>SELECT r.runner_id, COUNT(c.order_id) AS successful_deliveries<br>FROM runner_orders AS r<br>LEFT JOIN customer_orders AS c<br>    ON r.order_id = c.order_id<br>WHERE r.cancellation IS NULL<br>GROUP BY r.runner_id;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/0*XUBN9TLYo85M5WPe.png" /><figcaption>My result.</figcaption></figure><ul><li>Runner 1 completed 4 successful deliveries.</li><li>Runner 2 completed 3 successful deliveries.</li><li>Runner 3 completed 1 successful delivery.</li></ul><p>4. How many of each type of pizza was delivered?</p><p>I joined the customer_orders, pizza_name, and runner_orders tables for this. Then I used the COUNT function.</p><pre>SELECT c.pizza_id, p.pizza_name AS pizza_name, COUNT(c.pizza_id) AS count_of_pizza_type<br>FROM customer_orders AS c<br>INNER JOIN pizza_names AS p<br>    ON c.pizza_id = p.pizza_id<br>LEFT JOIN runner_orders AS r<br>     ON c.order_id = r.order_id<br>WHERE r.cancellation IS NULL<br>GROUP BY c.pizza_id, p.pizza_name;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/0*NCEppdWXjblB43XR.png" /><figcaption>My result.</figcaption></figure><ul><li>Meatlovers were delivered 9 times.</li></ul><p>Vegetarian was delivered 3 times.</p><p>5. How many Vegetarian and Meatlovers were ordered by each customer?</p><p>To solve this, I joined the customer_orders and pizza_name tables and then used the COUNT function.</p><pre>SELECT c.customer_id, p.pizza_name, COUNT(c.pizza_id) AS orders_by_customer<br>FROM customer_orders AS c<br>INNER JOIN pizza_names AS p<br>     ON c.pizza_id = p.pizza_id<br>GROUP BY c.customer_id, p.pizza_name<br>ORDER BY c.customer_id;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/0*P3Hrd0TqMZ_lg-Z_.png" /><figcaption>My result.</figcaption></figure><ul><li>Customer 101 ordered two Meatlovers pizzas and one Vegetarian pizza.</li><li>Customer 102 also ordered two Meatlovers pizzas and one Vegetarian pizza.</li><li>Customer 103 ordered three Meatlovers pizzas and one Vegetarian pizza.</li><li>Customer 104 ordered three Meatlovers pizzas and no vegetarian pizzas.</li><li>Customer 105 only ordered one type of vegetarian pizza.</li></ul><p>6. What was the maximum number of pizzas delivered in a single order?</p><p>I joined the customer_orders and runner_orders tables, then used a WITH clause to allow me to write more than one query, and then COUNT, and MAX aggregate functions to get the maximum number of pizzas delivered.</p><pre>WITH total_per_order AS (SELECT c.order_id, COUNT(c.order_id) AS total_of_single_order<br>FROM customer_orders AS c<br>LEFT JOIN runner_orders AS r<br>    ON c.order_id = r.order_id<br>WHERE r.cancellation IS NULL<br>GROUP BY c.order_id<br>ORDER BY total_of_single_order DESC)<br><br>SELECT MAX(total_of_single_order) AS max_single_order<br>FROM total_per_order;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/230/0*ia81VCvtoPwkgSP8.png" /><figcaption>My result.</figcaption></figure><ul><li>The most pizzas delivered in a single order was 3.</li></ul><p>7. For each customer, how many delivered pizzas had at least 1 change, and how many had no changes?</p><p>Here, I used the CASE WHEN function to calculate pizzas that had changes and those without changes, then used GROUP BY to categorize my output by customers.</p><pre>SELECT c.customer_id,<br> COUNT(CASE<br>WHEN c.exclusions IS NOT NULL THEN &#39;pizza_change&#39;<br>WHEN c.extras IS NOT NULL THEN &#39;pizza_change&#39;<br>END) AS delivery_with_changes,<br>COUNT(CASE<br>WHEN c.exclusions IS NULL THEN &#39;no_changes&#39;<br>WHEN c.extras IS NULL THEN &#39;no_changes&#39;<br>END) AS delivery_without_changes<br>FROM customer_orders AS c<br>LEFT JOIN runner_orders AS r<br>ON c.order_id = r.order_id<br>WHERE r.cancellation IS NULL<br>GROUP BY customer_id;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xKk1lDzNt2CJJ1pNT7GR0Q.png" /><figcaption>My result.</figcaption></figure><ul><li>For customer 101, there we 0 deliereies with changes, and 2 delivered without changes.</li><li>Customer 102, 0 deliveries with changes, 3 without changes.</li><li>Customer 103, 3 deliveries with changes, 3 without changes.</li><li>Customer 104, 2 deliveries with changes, 2 without changes.</li><li>Customer 105, 1 delivery with a change, 1 without change.</li></ul><p>8. How many pizzas were delivered that had both exclusions and extras?</p><p>I joined the customer_orders and runner_orders tables, then used the COUNT function to get the number of customers that had both exclusions and extras, and also used WHERE and AND to filter the NULL values our of my response.</p><pre>SELECT COUNT(c.pizza_id) AS pizza_with_exclusions_extras<br> FROM customer_orders AS c<br> LEFT JOIN runner_orders AS r<br>     ON c.order_id = r.order_id<br> WHERE r.cancellation IS NOT NULL<br> AND c.exclusions IS NOT NULL<br> AND c.extras IS NOT NULL;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/216/0*f55oYFrg7yYJQWez.png" /><figcaption>My result.</figcaption></figure><ul><li>Only 1 delivery had exclusions and extras made.</li></ul><p>9. What was the total volume of pizzas ordered for each hour of the day?</p><p>For this question, I used the EXTRACT function to get the hour of the day that orders were made and also used the COUNT aggregate function to get the number of orders made.</p><pre>SELECT EXTRACT(HOUR FROM order_time) AS hour_of_day, COUNT(pizza_id) AS total_orders<br>FROM customer_orders<br>GROUP BY EXTRACT(HOUR FROM order_time)<br>ORDER BY hour_of_day;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/0*IuCbZRcLsJ4kjQvK.png" /><figcaption>My result.</figcaption></figure><ul><li>A single order was made on the 11th hour of the day.</li><li>3 orders each on the 13th and 18th hour.</li><li>Another single order on the 19th hour.</li><li>3 orders each on the 21st and 23rd hour.</li></ul><p>10. What was the volume of orders for each day of the week?</p><p>I used the DAYNAME and COUNT functions here to extract the day of the week from the data, and the total number of orders made.</p><pre>SELECT DAYNAME(order_time) AS days_of_the_week, COUNT(pizza_id) AS total_orders<br>FROM customer_orders<br>GROUP BY DAYNAME(order_time)<br>ORDER BY days_of_the_week DESC;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/437/1*cumEKAymtJzma1Y6E_6q6g.png" /><figcaption>My result.</figcaption></figure><ul><li>5 orders were placed on Wednesday.</li><li>3 orders were placed on Thursday.</li><li>5 orders were placed on Saturday.</li><li>1 order was placed on Friday.</li></ul><h4>Section B. Runner and Customer Experience</h4><p>11. How many runners signed up for each 1 week period? (i.e. week starts 2021–01–01)</p><p>I used the EXTRACT function here to get the week of the month that signups were made. I also used COUNT and GROUP BY functions to determine the signups per week.</p><pre>SELECT EXTRACT(WEEK <br>FROM registration_date) AS week_of_month, COUNT(runner_id) AS runner_sign_up<br>GROUP BY EXTRACT(WEEK FROM registration_date)<br>ORDER BY week_of_month;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*CXjXZGsA_rO540QYhF5_nQ.png" /><figcaption>My result.</figcaption></figure><ul><li>In week 1 (0), 1 runner signed up.</li><li>In week 2 (1), 2 runners signed up.</li><li>In week 3 (2), 1 runner signed up.</li></ul><p>12. What was the average time in minutes it took for each runner to arrive at the Pizza Runner HQ to pick up the order?</p><p>Here, I used the AVERAGE function to calculate the average time it took each runner to arrive, and also the TIMESTAMPDIFF function to calculate the difference between the order time and pickup time (to arrive at the time it took runners to arrive).</p><pre>SELECT r.runner_id,<br>ROUND(AVG(TIMESTAMPDIFF(MINUTE, c.order_time, r.pickup_time)),2) AS  average_minutes<br>FROM runner_orders r<br>LEFT JOIN customer_orders c<br>ON r.order_id = c.order_id<br>GROUP BY r.runner_id;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/0*X8eTNBjbi3htdtp9.png" /><figcaption>My result.</figcaption></figure><ul><li>The average time for runner 1 was 15.33.</li><li>Runner was 23.40.</li><li>Runner 3 was 10.00.</li></ul><p>13. Is there any relationship between the number of pizzas and how long the order takes to prepare?</p><p>I used the TIMESTAMPDIFF function to calculate the number of pizza orders versus the time it took to make them (order time minus pickup time). I went on to use the COUNT function to count the number of pizza orders made, then used WHERE, GROUP BY, and ORDER BY to filter the pizza orders.</p><pre>SELECT COUNT(c.pizza_id) AS pizza_numbers, <br>TIMESTAMPDIFF(MINUTE, c.order_time, r.pickup_time) AS preparation_time<br>FROM customer_orders AS c<br>LEFT JOIN runner_orders AS r<br>ON c.order_id = r.order_id<br>WHERE c.order_time IS NOT NULL<br>AND r.pickup_time IS NOT NULL<br>GROUP BY c.order_time, r.pickup_time<br>ORDER BY pizza_numbers;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*3rbmz_egguu8dWUXWhWZOg.png" /><figcaption>My result.</figcaption></figure><ul><li>From my result, there appears to be a link between the number of pizzas and the time it took to prepare them. As we can see, the more pizzas ordered, the longer the preparation time appeared to be.</li></ul><p>14. What was the average distance traveled for each customer?</p><p>I used the ROUND and AVERAGE functions here to calculate the distance runners traveled to make deliveries.</p><pre>SELECT c.customer_id, ROUND(AVG(r.distance),2) AS avg_distance_km<br>FROM customer_orders AS c<br>LEFT JOIN runner_orders AS r<br>ON c.order_id = r.order_id<br>GROUP BY c.customer_id;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/0*44p32C63gnBP-SGs.png" /><figcaption>My result.</figcaption></figure><ul><li>Customer 101&#39;s average was 20km.</li><li>Customer 102’s average was 16.73km.</li><li>Customer 103’s average was 23.4km.</li><li>Customer 104’s average was 10km.</li><li>Customer 105’s average was 25km.</li></ul><p>15. What was the difference between the longest and shortest delivery times for all orders?</p><p>Here, I did a subtraction, using the MAX and MIN aggregate functions, to get the difference between the longest and shortest times for all orders.</p><pre>SELECT MAX(duration) - MIN(duration) AS time_difference<br>FROM runner_orders;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*Kaqg1EZXkYAnQtEbGoKHIg.png" /><figcaption>My result.</figcaption></figure><ul><li>The time difference was 30 minutes.</li></ul><p>16. What was the average speed for each runner for each delivery and do you notice any trend for these values? (They maintained the same speed for each delivery)</p><p>I used the AVERAGE aggregate function to calculate the speed for each runner. Also used ROUND to get my result in whole numbers.</p><pre>SELECT r.runner_id, c.order_id, ROUND(AVG(r.distance/ r.duration ),2) <br>AS avg_runner_speed<br>FROM runner_orders AS r<br>JOIN customer_orders AS c<br>ON r.order_id = c.order_id<br>WHERE r.distance IS NOT NULL<br>AND r.duration IS NOT NULL<br>GROUP BY r.runner_id, c.order_id<br>ORDER BY r.runner_id;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*3udhgl0l4BgiZOd_Lur6MQ.png" /><figcaption>My result.</figcaption></figure><ul><li>We have an average speed of 0.62km — 1km for runner 1</li><li>0.58km — 1.56km for runner 2</li><li>And 0.67km for runner 3.</li></ul><p>17. What is the successful delivery percentage for each runner?</p><p>I used the COUNT aggregate function to get the total successful deliveries and CASE WHEN to help fulfill the condition of successful deliveries. I finished by using GROUP BY to categorize my result by runnner.</p><pre>WITH count_table AS ( SELECT r.runner_id,<br>COUNT(CASE WHEN r.cancellation IS NULL THEN &#39;successful_deliveries&#39;<br>END) AS successful_delivery,<br>COUNT(CASE WHEN order_id IS NOT NULL THEN &#39;total_order&#39;<br>END) AS total_orders<br>FROM runner_orders r<br>GROUP BY r.runner_id)<br>SELECT runner_id, <br>ROUND((successful_delivery / total_orders) * 100,2) AS success_percentage<br>FROM count_table;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/0*gRz5d7e8UXH3JvDt.png" /><figcaption>My result.</figcaption></figure><ul><li>Runner 1 had a 100 percent success rate.</li><li>Runner 2 had a 75 percent success rate.</li><li>Runner 3 had a 50 percent success rate.</li></ul><p><em>That’s all from me for now. Thanks for sticking with me and see you in the next one.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e3475d926d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[8-Week SQL Challenge: Case Study #1: Danny’s Diner]]></title>
            <link>https://medium.com/@adebolaanimashaun/8-week-sql-challenge-case-study-1-dannys-diner-f48460f4a3b0?source=rss-95bf8d798f22------2</link>
            <guid isPermaLink="false">https://medium.com/p/f48460f4a3b0</guid>
            <dc:creator><![CDATA[adebola animashaun]]></dc:creator>
            <pubDate>Tue, 26 Nov 2024 10:32:54 GMT</pubDate>
            <atom:updated>2024-11-26T10:32:54.167Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello Everyone!</p><p>I spent the past few months actively learning SQL and decided to try my hands at some challenges. I came across the 8-week SQL Challenge and I’m excited to walk you through how I tackled some of the case studies.</p><p>Let’s begin, shall we?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4oCtgElA5ZUyU6US.png" /></figure><p><strong>Introduction</strong></p><p>Danny seriously loves Japanese food, so at the beginning of 2021, he decides to embark upon a risky venture and opens up a cute little restaurant that sells his 3 favorite foods: sushi, curry, and ramen.</p><p>Danny’s Diner needs your assistance to help the restaurant stay afloat — the restaurant has captured some very basic data from its few months of operation but has no idea how to use its data to help it run the business.</p><h4>Problem Statement</h4><p>Danny wants to use the data to answer a few simple questions about his customers, especially about their visiting patterns, how much money they’ve spent, and also which menu items are their favorite. Having this deeper connection with his customers will help him deliver a better and more personalized experience for his loyal customers.</p><p>He plans on using these insights to help him decide whether he should expand the existing customer loyalty program — additionally, he needs help to generate some basic datasets so his team can easily inspect the data without needing to use SQL.</p><p>Danny has provided you with a sample of his overall customer data due to privacy issues — but he hopes that these examples are enough for you to write fully functioning SQL queries to help him answer his questions!</p><p>We are provided with 3 datasets/tables for this case study:</p><ul><li>sales</li><li>menu</li><li>members</li></ul><p>You can inspect the entity relationship diagram and example data below for context.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*q3SofQ5b6kVWGMPZ.png" /></figure><p><strong>Case Study Questions</strong></p><ol><li>What is the total amount each customer spent at the restaurant?</li><li>How many days has each customer visited the restaurant?</li><li>What was the first item from the menu purchased by each customer?</li><li>What is the most purchased item on the menu and how many times was it purchased by all customers?</li><li>Which item was the most popular for each customer?</li><li>Which item was purchased first by the customer after they became a member?</li><li>Which item was purchased just before the customer became a member?</li><li>What were the total items and amounts spent by each member before they became a member?</li><li>If each $1 spent equates to 10 points and sushi has a 2x points multiplier — how many points would each customer have?</li><li>In the first week after a customer joins the program (including their join date) they earn 2x points on all items, not just sushi — how many points do customers A and B have at the end of January?</li></ol><p>Let&#39;s jump right into it! For context, I use MySQL workbench for my queries.</p><p><strong>Solution</strong></p><ol><li>What is the total amount each customer spent at the restaurant?</li></ol><p>First, I joined the Sales and Menu tables together, then used the SUM aggregate function to get the total amount spent by each customer. We finally used GROUP BY to categorize the summed amount by customer.</p><pre>SELECT s.customer_id, SUM( m.price) AS total_amount_spent<br>FROM sales AS s<br>INNER JOIN menu AS m<br>ON s.product_id = m.product_id<br>GROUP BY s.customer_id;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*IKeSjebAPTdchEuAqg58qg.png" /><figcaption>My result.</figcaption></figure><ul><li>Customer A spent a total of $76</li><li>Customer B spent $74</li><li>Customer C spent $36</li></ul><p>2. How many days has each customer visited the restaurant?</p><p>I used the COUNT aggregate function and then DISTINCT to count the order_date column in the Sales table uniquely, and then I finally used GROUP BY to categorize by customer.</p><pre>SELECT customer_id, COUNT(DISTINCT order_date) AS total_days_visited<br>FROM sales<br>GROUP BY customer_id; </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*x7Ny4K9EO-2ME5Wz9SwGww.png" /><figcaption>My result.</figcaption></figure><ul><li>Customer A visited 4 days</li><li>Customer B visited 6 days</li><li>Customer C visited 2 days</li></ul><p>3. What was the first item from the menu purchased by each customer?</p><p>I used the DENSE_RANK () window function and CTE (WITH clause) for this. I joined the Sales and Menu tables, and used PARTITION BY customer_id to group the ranking by customer, and then used ORDER BY order_date to sort the purchases by date.</p><p>I finally used the WITH clause to create a temporary table and extend my query. I then filtered using the WHERE clause to get the first item from the menu and used GROUP BY to categorize the items by customer/product_name.</p><pre>WITH first_items AS (SELECT s.customer_id, m.product_name, s.order_date,<br>   DENSE_RANK() OVER(PARTITION BY customer_id ORDER BY order_date) AS first_item_purchased<br>   FROM sales AS s<br>   JOIN menu AS m<br>     ON s.product_id = m.product_id)<br>        <br>   SELECT customer_id, product_name<br>   FROM first_items<br>   WHERE first_item_purchased = 1<br>   GROUP BY customer_id, product_name;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*rbGXan9dIEGH5XNRfhOrbg.png" /><figcaption>My result.</figcaption></figure><ul><li>For Customer A, the first items purchased were sushi and curry</li><li>For Customer B, the first item purchased was a curry</li><li>For Customer C, the first item purchased was ramen.</li></ul><p>4. What is the most purchased item on the menu and how many times was it purchased by all customers?</p><p>For this question, I joined the Sales and Menu tables, then used the DENSE_RANK() window function and CTE again. We ranked the total number of customer purchases from most to least frequently purchased, then used the WHERE clause to return the items purchased the most.</p><pre>WITH count_purchase AS ( SELECT m.product_name, <br>  COUNT(s.product_id) AS number_of_times_purchased,<br>  DENSE_RANK() OVER(ORDER BY COUNT(s.product_id) DESC) AS  purchase_ranking<br>  FROM sales s<br>  INNER JOIN menu m<br>          ON s.product_id = m.product_id<br>  GROUP BY m.product_name)<br><br>  SELECT product_name, number_of_times_purchased<br>  FROM count_purchase<br>  WHERE purchase_ranking = 1;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*c_1NGHaum7Ddaldg-Je4Ag.png" /><figcaption>My result.</figcaption></figure><p>The most Frequently purchased item = Ramen, which was purchased 8 times.</p><p>5. Which item was the most popular for each customer?</p><p>To tackle this, I joined the Sales and Menu tables and used the DENSE_RANK widow function to get the most popular item. I used the COUNT function to get the number of purchases and then used the ORDER BY for sorting. I finally used GROUP BY to categorize purchases by customers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*BhB1mQpN3fWh1Wbx8NYdng.png" /><figcaption>My result.</figcaption></figure><ul><li>For Customer A, the most frequently purchased item was ramen which was purchased 3 times.</li><li>For Customer B, the most frequently purchased items were curry, sushi, and ramen, and were purchased 2 times each.</li><li>For Customer C, only ramen was purchased, 3 times.</li></ul><p>6. Which item was purchased first by the customer after they became a member?</p><p>First, I joined the Sales, Members, and Menu tables, then used the DENSE_RANK() window function and CTE to rank items purchased by customers.</p><p>I used the WHERE clause to filter the order and join date to ensure we’re aggregating only the period after the customers became members. I also used ORDER BY to sort the ‘order_date’ from the earliest date, so I could get the items purchased after becoming members.</p><pre>WITH ranked_orders AS (SELECT s.customer_id, mu.product_name, s.order_date, m.join_date, <br>  DENSE_RANK () OVER(PARTITION BY customer_id ORDER BY order_date) AS first_order_as_member<br>  FROM sales AS s<br>  JOIN members AS m<br>    ON s.customer_id = m.customer_id<br>  JOIN menu AS mu<br>    ON s.product_id = mu.product_id<br>  WHERE order_date &gt;= join_date)<br>   <br>  SELECT customer_id, product_name<br>  FROM ranked_orders<br>  WHERE first_order_as_member = 1;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/1*i8FI1wgc_o9mXIrtoipgrw.png" /><figcaption>My result.</figcaption></figure><ul><li>Customer A purchased a curry</li><li>Customer B purchased sushi.</li></ul><p>7. Which item was purchased just before the customer became a member?</p><p>Same with the previous question, I joined the Sales, Members, and Menu tables, then used the DENSE_RANK() window function and CTE to rank items purchased by customers. I used the WHERE clause to filter the order and join date to ensure we’re aggregating only the period after the customers became members.</p><p>I also used ORDER BY DESC to sort the ‘order_date’ to start from the latest date this time, so I could get the items purchased by customers before becoming members.</p><pre>WITH ranked_items AS <br>  (SELECT s.customer_id, mu.product_name, s.order_date, m.join_date, <br>  DENSE_RANK () OVER(PARTITION BY customer_id <br>  ORDER BY order_date DESC) AS first_order_as_member<br>  FROM sales AS s<br>  JOIN members AS m<br>    ON s.customer_id = m.customer_id<br>  JOIN menu AS mu<br>    ON s.product_id = mu.product_id<br>  WHERE order_date &lt; join_date)<br>       <br>  SELECT customer_id, product_name<br>  FROM ranked_items<br>  WHERE first_order_as_member = 1;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*FQLA5z-6Jq2QlVQUBRBmcw.png" /><figcaption>My result.</figcaption></figure><ul><li>Customer A purchased sushi and a curry before becoming a member.</li><li>Customer B purchased sushi before becoming a member.</li></ul><p>8. What are the total items and amount spent for each member before they became a member?</p><p>I joined the Sales, Members, and Menu tables, then used the WHERE clause to filter the order and join date to ensure we’re aggregating only the period before the customers became members. I used a WITH clause to expand my query and partitioned the response by customer.</p><p>I also used the SUM and COUNT aggregate functions to calculate the total amount spent and the number of items purchased for each customer, before they became members.</p><pre>WITH summed_item_price AS <br>  (SELECT s.product_id, s.customer_id, s.order_date, m.join_date, <br>  SUM(price) OVER(PARTITION BY customer_id) AS total_price<br>  FROM sales AS s<br>  JOIN members AS m<br>    ON s.customer_id = m.customer_id<br>  JOIN menu AS mu<br>    ON s.product_id = mu.product_id<br>  WHERE order_date &lt; join_date)<br><br>  SELECT customer_id, total_price, count(product_id) AS total_items<br>  FROM summed_item_price<br>  GROUP BY customer_id, total_price;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*YSy3nGQSMBB_2WhRtB3LwA.png" /><figcaption>My result.</figcaption></figure><ul><li>Customer A purchased two items and spent $25 before they became a member.</li><li>Customer B purchased three items and spent $40 before they became a member.</li></ul><p>9. If each $1 spent equates to 10 points and sushi has a 2x points multiplier — how many points would each customer have?</p><p>For this question, I joined the Sales and Menu tables, then went ahead to use a CASE function to be able to append and aggregate the value of points allotted. Then I used the SUM function to add the multiplied value of price and points per product.</p><p>Finally, I used GROUP BY to categorize my response by customer.</p><pre>WITH points_of_items AS (SELECT s.customer_id, m.product_name, m.price,<br>  CASE WHEN s.product_id = 1 THEN 20<br>  WHEN s.product_id = 2 THEN 10<br>  WHEN s.product_id = 3 THEN 10<br>  END AS points_per_product<br>  FROM sales AS s<br>  JOIN menu AS m<br>    ON s.product_id = m.product_id)<br>        <br>  SELECT customer_id, SUM(price * points_per_product)<br>  FROM points_of_items<br>  GROUP BY customer_id;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*Q64rRld7KAlgzVHAdZp8xw.png" /><figcaption>My result.</figcaption></figure><ul><li>Customer A has 860 points</li><li>Customer B has 940 points</li><li>Customer C has 360 points</li></ul><p>10. In the first week after a customer joins the program (including their join date) they earn 2x points on all items, not just sushi, how many points do customers A and B have at the end of January?</p><p>I used the DATE_ADD function to calculate the first week after customers joined the program, then used the SUM and CASE functions to get the total points for each customer.</p><pre>WITH date_table AS <br> (SELECT s.customer_id, s.product_id, m.product_name, s.order_date, <br> ms.join_date, m.price, <br> DATE_ADD(ms.join_date, INTERVAL 6 DAY) AS first_week  <br> FROM sales s<br> JOIN menu m<br>   ON s.product_id = m.product_id<br> JOIN members ms<br>   ON s.customer_id = ms.customer_id<br> WHERE EXTRACT(MONTH FROM s.order_date) = 1)<br>   <br> SELECT customer_id, SUM(CASE <br> WHEN order_date BETWEEN join_date AND first_week THEN price*2*10<br> WHEN product_name = &#39;sushi&#39; THEN price*2*10<br> ELSE price*10 <br> END) AS Customer_Points<br> FROM date_table <br> WHERE order_date &lt; first_week<br> GROUP BY customer_id<br> ORDER BY customer_id;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/0*CiBHIkTG1wNJFyGw.png" /><figcaption>My result.</figcaption></figure><p>By the end of January:</p><ul><li>Customer A has 1370 points</li><li>Customer B has 700 points</li></ul><p><em>That&#39;s all from me at this time! Many thanks for riding with me to the end of this case study. I look forward to attempting the next one.</em></p><p><em>Cheers!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f48460f4a3b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>