<?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 Emine Tolun on Medium]]></title>
        <description><![CDATA[Stories by Emine Tolun on Medium]]></description>
        <link>https://medium.com/@eminetolun?source=rss-cab3d3c96832------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*b3W8YroYJc5iiWIjZzElTA.jpeg</url>
            <title>Stories by Emine Tolun on Medium</title>
            <link>https://medium.com/@eminetolun?source=rss-cab3d3c96832------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 23:49:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@eminetolun/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: Case Study #3 -Foodie — Fi]]></title>
            <link>https://medium.com/@eminetolun/8-weeks-sql-challenge-case-study-3-foodie-fi-b573494ebc75?source=rss-cab3d3c96832------2</link>
            <guid isPermaLink="false">https://medium.com/p/b573494ebc75</guid>
            <dc:creator><![CDATA[Emine Tolun]]></dc:creator>
            <pubDate>Thu, 16 Jun 2022 08:38:05 GMT</pubDate>
            <atom:updated>2022-06-16T10:25:19.701Z</atom:updated>
            <content:encoded><![CDATA[<h3>8 Weeks SQL Challenge: Case Study #3 -Foodie — Fi</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1HimU-u3bCfI2ZevLRdYDg.png" /></figure><p>You can find this challenge <a href="https://8weeksqlchallenge.com/case-study-3/">here</a>. Thank you Danny Ma for the case study.</p><h4>Introduction</h4><p>Subscription based businesses are super popular and Danny realised 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 finds 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><h4>Available Data</h4><p>Danny has shared the data design for Foodie-Fi and also short descriptions on 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><h4>Entity Relationship Diagram</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*ZEF3466ykdwVg3N8fHvYLg.png" /></figure><h4>Table 1: plans</h4><p>Customers can choose which plans to join Foodie-Fi when they first sign up.</p><p>Basic plan customers have limited access and can only stream their videos and is only available monthly at $9.90</p><p>Pro plan customers have no watch time limits and are able to download videos for offline viewing. Pro plans start at $19.90 a month or $199 for an annual subscription.</p><p>Customers can sign up to an initial 7 day free trial will automatically continue with the pro monthly subscription plan unless they cancel, downgrade to basic or upgrade to an annual pro plan at any point during the trial.</p><p>When customers cancel their Foodie-Fi service — they will have a churn plan record with a null price but their plan will continue until the end of the billing period.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*XH7kIgNm5fl4h0_7T_LoqQ.png" /></figure><h4>Table 2: subscriptions</h4><p>Customer subscriptions show the exact date where their specific plan_id starts.</p><p>If customers downgrade from a pro plan or cancel their subscription — the higher plan will remain in place until the period is over — the start_date in the subscriptions table will reflect the date that the actual plan changes.</p><p>When customers upgrade their account from a basic plan to a pro or annual pro plan — the higher plan will take effect straightaway.</p><p>When customers churn — they will keep their access until the end of their current billing period but the start_date will be technically the day they decided to cancel their service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*B7VEVr7FhPQ7wm3UkbCY0w.png" /></figure><h3><strong>Merging plans table and subscriptions table</strong></h3><pre>CREATE TEMP TABLE customers AS<br>SELECT s.customer_id, s.plan_id, p.plan_name, s.start_date, p.price FROM foodie_fi.subscriptions s<br>JOIN foodie_fi.plans p<br>ON s.plan_id = p.plan_id<br>ORDER BY s.customer_id;</pre><pre>SELECT * FROM customers;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*n8kn6UFz7xf-2Gb-P1AXkw.png" /></figure><p>I will answer all questions using the <strong>customers </strong>table.</p><h3>A. Customer Journey</h3><p>Based off the 8 sample customers provided in the sample from the subscriptions table, write a brief description about each customer’s onboarding journey.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*umfMbM1oKe4AHpwHVmDC6A.png" /></figure><ul><li>Customer 10 started the free trial on 19 Sep 2020 and subscribed to the pro monthly plan on 26 Sep 2020 after the 7-days trial has ended.</li><li>Customer 498 started the fee trial on 13 Nov 2020, subscribed to the basic monthly plan on 20 Nov 2020 and churned on 3 Jun 2021.</li></ul><h3>B. Data Analysis Questions</h3><p><strong>1. How many customers have Foodie-Fi ever had?</strong></p><pre>SELECT COUNT(DISTINCT(s.customer_id)) FROM customers</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/120/1*JleYJ7yfj5pxK-B3USJeJQ.png" /></figure><ul><li>Foodie-Fi has 1000 different customers.</li></ul><p><strong>2. What is the monthly distribution of </strong><strong>trial plan </strong><strong>start_date values for our dataset - use the start of the month as the group by value.</strong></p><p>Date is separated into months with the DATE_PART function. Only trials are selected with the WHERE.</p><pre>SELECT <br> DATE_PART(‘month’,start_date) AS month_date, <br> TO_CHAR(start_date, ‘Month’) AS month_name, <br> COUNT(plan_id)  AS total_plan<br>FROM customers<br>WHERE plan_name = ‘trial’<br>GROUP BY month_date, month_name ;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*C-F54KPuJ92LkEPI-qFu9Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*s8ztrHIddBJNdStpLnF-zA.png" /></figure><ul><li>Trial package was started most in March.</li></ul><p><strong>3. What plan </strong><strong>start_date values occur after the year 2020 for our dataset? Show the breakdown by count of events for each </strong><strong>plan_name.</strong></p><p>The question is asking for the counts of plans after the year 2020. So, filter out values with a start date greater than 2020–12–31.</p><pre>SELECT plan_id, plan_name, COUNT(plan_name) AS count_of_events <br>FROM customers <br>WHERE start_date &gt;= ‘2021–01–01’<br>GROUP BY plan_id , plan_name<br>ORDER BY plan_id;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/349/1*-r9Ouo4pPPuw_lCr_INjuQ.png" /></figure><p><strong>4. What is the customer count and percentage of customers who have churned rounded to 1 decimal place?</strong></p><pre>SELECT COUNT(*) AS churn_id, <br>ROUND(( COUNT(*)::NUMERIC / (SELECT COUNT(DISTINCT customer_id) FROM foodie_fi.subscriptions))::NUMERIC * 100,2) AS percentage<br>FROM customers<br>WHERE plan_name = ‘churn’</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/174/1*zhhHNymBsDFpYThgS0wauA.png" /></figure><ul><li>307 pcs customers churned. The percentage rate is %30, I think this is high a rate. Strategies should be determined in order not to lose customers.</li></ul><p><strong>5. How many customers have churned straight after their initial free trial,what percentage is this rounded to the nearest whole number?</strong></p><pre>WITH ranking_cte AS(<br>SELECT * , DENSE_RANK() OVER(PARTITION BY customer_id ORDER BY start_date ) AS rn FROM customers<br>)<br>SELECT COUNT(*) as churn_count, <br>ROUND(( COUNT(*)::NUMERIC / (SELECT COUNT(DISTINCT customer_id) FROM foodie_fi.subscriptions))::NUMERIC * 100) AS percentage <br>FROM ranking_cte<br>WHERE rn = 2 AND plan_name = ‘churn’</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/195/1*ZDrl_6RwS6ElOt3VRK9PsQ.png" /></figure><p><strong>6. What is the number and percentage of customer plans after their initial free trial?</strong></p><pre>WITH ranking_cte AS(<br>SELECT * , DENSE_RANK() OVER(PARTITION BY customer_id ORDER BY start_date ) AS rn FROM customers) <br>SELECT plan_id , plan_name AS next_plan, <br>COUNT(*) AS changes, <br>ROUND((COUNT(*)::NUMERIC /(SELECT COUNT(DISTINCT customer_id) FROM foodie_fi.subscriptions))::NUMERIC * 100,2) AS percentage <br>FROM ranking_cte<br>WHERE rn = 2 <br>GROUP BY plan_id, plan_name;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*tIlt0XCuLjjC0oxJs3otWA.png" /></figure><ul><li>54.60% of customers continued to use the basic monthly plan after the free trial.</li><li>32.50% of customers continued to use the pro monthly plan after the free trial.</li><li>3.70% of customers continued to use the pro annual plan after the free trial.</li><li>9.20% of customers churned after the free trial.</li></ul><p><strong>7. What is the customer count and percentage breakdown of all 5 plan_name values at 2020–12–31?</strong></p><pre>WITH lastdate_cte AS(<br>SELECT customer_id, MAX(start_date) AS last_date FROM customers<br>GROUP BY customer_id<br>ORDER BY customer_id<br>)<br>SELECT c.plan_name, COUNT(c.plan_name) AS plan_count,<br>ROUND((COUNT(*)::NUMERIC /(SELECT COUNT(DISTINCT customer_id) FROM customers))::NUMERIC * 100,2) AS percentage <br>FROM customers AS c<br>JOIN lastdate_cte AS l<br>ON c.customer_id = l.customer_id<br>WHERE c.start_date = l.last_date and l.last_date &lt;= ‘2020–12–31’<br>GROUP BY c.plan_name</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/1*ct5fwJFBhu9a0LdN-GLZdA.png" /></figure><p><strong>8. How many customers have upgraded to an annual plan in 2020?</strong></p><pre>SELECT COUNT(DISTINCT(customer_id)) AS annual_cus FROM customers<br>WHERE start_date &lt;= &#39;2020-12-31&#39; AND plan_id = &#39;3&#39;;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/99/1*csrc9Ul4C4gFrm04sCd8JA.png" /></figure><ul><li>195 customers upgraded to an annual plan in 2020.</li></ul><p><strong>9. How many days on average does it take for a customer to an annual plan from the day they join Foodie-Fi?</strong></p><pre>WITH trial_cte AS(<br>SELECT * FROM customers<br>WHERE plan_id = &#39;0&#39; <br>), annual_cte AS(<br>SELECT * FROM customers<br>WHERE plan_id = &#39;3&#39;)<br>SELECT ROUND(AVG(a.start_date - t.start_date)) AS avg_plan <br>FROM trial_cte AS t<br>JOIN annual_cte AS a <br>ON t.customer_id = a.customer_id;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/81/1*y3kgEVud77GpuDnXUvxA2g.png" /></figure><ul><li>A customer switches to an annual plan after an average of 105 days.</li></ul><p><strong>10. Can you further breakdown this average value into 30 day periods (i.e. 0–30 days, 31–60 days etc)</strong></p><pre>WITH trial_plan AS <br>(SELECT <br> customer_id, <br> start_date AS trial_date<br>FROM customers<br>WHERE plan_id = ‘0’<br>),<br>annual_plan AS<br>(SELECT <br> customer_id, <br> start_date AS annual_date<br>FROM customers<br>WHERE plan_id =’3&#39;<br>),<br>bins AS <br>(SELECT <br> WIDTH_BUCKET(ap.annual_date — tp.trial_date, 0, 360 , 12) AS avg_days_to_upgrade<br>FROM trial_plan tp<br>JOIN annual_plan ap<br> ON tp.customer_id = ap.customer_id)<br>SELECT <br> ((avg_days_to_upgrade — 1) * 30 || ‘ — ‘ || (avg_days_to_upgrade) * 30) || ‘ days’ AS breakdown, <br> COUNT(*) AS customers_count<br>FROM bins<br>GROUP BY avg_days_to_upgrade<br>ORDER BY avg_days_to_upgrade;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/227/1*iKMdvIqI549uV4dP2DptZw.png" /></figure><p><strong>11. How many customers were downgraded from a pro monthly to a basic monthly plan in 2020?</strong></p><pre>WITH ranking_cte AS(<br>SELECT * , DENSE_RANK() OVER(PARTITION BY customer_id ORDER BY start_date ) AS rn FROM customers<br>where plan_id != ‘0’) <br>SELECT COUNT(*) FROM ranking_cte <br>WHERE (rn = 1 AND plan_id = ‘2’) AND (rn = 2 and plan_id = ‘1’)<br>GROUP BY customer_id;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/64/1*aXIC7lonVsQ6vn3nPaEojw.png" /></figure><ul><li>Nobody has downgraded from a pro monthly to a basic plan in 2020.</li></ul><p>For your suggestions, you can reach me <a href="https://www.linkedin.com/in/emine-tolun/">here</a>. You can find all the codes <a href="https://github.com/eminetolun/8WeekSQLChallenge/blob/main/Case_Study3.sql">here</a>.</p><p>Thank you for reading. See you in the fourth case. :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b573494ebc75" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[8 Weeks SQL Challenge: Case Study #2 -Pizza Runner]]></title>
            <link>https://medium.com/@eminetolun/8-weeks-sql-challenge-case-study-2-pizza-runner-8822566ec7d1?source=rss-cab3d3c96832------2</link>
            <guid isPermaLink="false">https://medium.com/p/8822566ec7d1</guid>
            <dc:creator><![CDATA[Emine Tolun]]></dc:creator>
            <pubDate>Tue, 24 May 2022 20:44:39 GMT</pubDate>
            <atom:updated>2022-05-24T20:45:12.783Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_qg3jgz0W4aJ8AQEFyNesw.png" /></figure><p>You can find this challenge <a href="https://8weeksqlchallenge.com/case-study-2/">here</a>. Thank you Danny Ma for the case study.</p><h3>Introduction</h3><p>Did you know that over <strong>115 million kilograms</strong> of pizza is consumed daily worldwide??? (Well according to Wikipedia anyway…)</p><p>Danny was scrolling through his Instagram feed when something really 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><h3>Available Data</h3><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><h3>Entity Relationship Diagram</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*k96dX3Ex1ACK-6sxrfMKIA.png" /></figure><h4>Table 1: runners</h4><p>The runners table shows the registration_date for each new runner</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/211/1*XjqaUrDIbG_OqMuA2oubiw.png" /></figure><h4>Table 2: customer_orders</h4><p>Customer pizza orders are captured in the customer_orders table with 1 row for each individual pizza that is part of the order.</p><p>The pizza_id relates to the type of pizza which was ordered whilst the exclusions are the ingredient_id values which should be removed from the pizza and the extras are the ingredient_id values which need to be added to the pizza.</p><p>Note that customers can order multiple pizzas in a single order with varying exclusions and extras values even if the pizza is the same type!</p><p>The exclusions and extras columns will need to be cleaned up before using them in your queries</p><pre>SELECT * FROM pizza_runner.customer_orders;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*VVshWx0KHBpcCqfaOLV9hw.png" /></figure><blockquote><em>customer_orders table has ‘null’, null values. I am creating a new temporary table named “</em><strong><em>customer_orders_temp</em></strong><em>” by data manipulation . I used this table when solving questions.</em></blockquote><pre>CREATE TEMP TABLE customer_orders_temp AS <br>SELECT <br>   order_id , customer_id, pizza_id,<br>   CASE <br>       WHEN exclusions IS null OR exclusions LIKE &#39;null&#39; THEN &#39;&#39;<br>    ELSE exclusions<br>    END exclusions,<br>   CASE  <br>    WHEN extras IS null OR extras LIKE &#39;null&#39; THEN &#39;&#39;<br>    ELSE extras<br>   END extras, order_time FROM pizza_runner.customer_orders;</pre><pre>SELECT * FROM customer_orders_temp;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*ZeWoUtKNAbqlfLWGhbxNEw.png" /></figure><h4>Table 3: runner_orders</h4><p>After each orders are received through the system — they are assigned to a runner — however not all orders are fully completed and can be cancelled by the restaurant or the customer.</p><p>The pickup_time is the timestamp at which the runner arrives at the Pizza Runner headquarters to pick up the freshly cooked pizzas. The distance and duration fields are related to how far and long the runner had to travel to deliver the order to the respective customer.</p><p>There are some known data issues with this table so be careful when using this in your queries — make sure to check the data types for each column in the schema SQL!</p><pre>SELECT * FROM pizza_runner.runner_orders;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*es1UJU8xt4XWhSFTQ9gRPQ.png" /></figure><blockquote><em>runner_orders table has expressions like “null”, km, minutes, mins etc. Time variable (pickup_time), distance, duration variables are character. I am creating a new temporary table named “</em><strong><em>runner_orders_temp</em></strong><em>”. I used this table when solving questions.</em></blockquote><pre>CREATE TEMP TABLE runner_orders_temp AS<br>SELECT order_id,runner_id,<br>CASE WHEN pickup_time IS null OR pickup_time LIKE ‘null’ THEN ‘’ <br> ELSE pickup_time<br> END pickup_time,<br>CASE when distance IS null OR distance LIKE ‘null’ THEN ‘’<br>WHEN distance LIKE ‘%km’ THEN TRIM(‘km’from distance)<br>ELSE distance<br>END AS distance ,</pre><pre>CASE <br>WHEN duration IS null OR duration LIKE ‘null’ THEN ‘’<br>WHEN duration LIKE ‘%minute’ THEN TRIM(‘minute’ from duration)<br>WHEN duration LIKE ‘%minutes’ THEN TRIM(‘minutes’ from duration)<br>WHEN duration LIKE ‘%mins’ THEN TRIM(‘mins’ from duration)<br>ELSE duration<br>END AS duration,</pre><pre>CASE <br>WHEN cancellation IS null OR cancellation LIKE ‘null’ THEN ‘’<br>ELSE cancellation<br>END AS cancellation<br>FROM pizza_runner.runner_orders;</pre><pre>ALTER TABLE runner_orders_temp<br>ALTER COLUMN pickup_time  TYPE  TIMESTAMP USING(CASE WHEN pickup_time = &#39;&#39; THEN null ELSE pickup_time:: TIMESTAMP END),<br>ALTER COLUMN distance TYPE FLOAT USING(CASE WHEN distance = &#39;&#39; THEN NULL ELSE distance:: FLOAT END),<br>ALTER COLUMN duration TYPE INT USING(CASE WHEN duration = &#39;&#39; THEN NULL ELSE duration:: INT END);</pre><pre>SELECT * FROM runner_orders_temp;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*rci85A4La9XWO1zzCqz_BQ.png" /></figure><h4>Table 4: pizza_names</h4><p>At the moment — Pizza Runner only has 2 pizzas available the Meat Lovers or Vegetarian!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/178/1*9OKH2koUkk0x6rFfrSIY6w.png" /></figure><h4>Table 5: pizza_recipes</h4><p>Each pizza_id has a standard set of toppings which are used as part of the pizza recipe.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/202/1*dNazKuP2g0MT36rmt7djCQ.png" /></figure><h4>Table 6: pizza_toppings</h4><p>This table contains all of the topping_name values with their corresponding topping_id value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/198/1*sj2_lmFoVJzck-ONqQW9ig.png" /></figure><h3>Case Study Questions</h3><p>I used PostgreSQL for all questions and answers.</p><p>Let’s start answering! :)</p><h3>A. Pizza Metrics</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*Z_vlmvZwIQbpU2Yrrnuipw.jpeg" /></figure><h4>1 ) How many pizzas were ordered?</h4><pre>SELECT COUNT(pizza_id) FROM customer_orders_temp;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/92/1*NFja5YrYRXuieDtnGg-9aQ.png" /></figure><ul><li>Customers ordered 14 pcs pizzas.</li></ul><h4>2) How many unique customer orders were made?</h4><pre>SELECT COUNT(DISTINCT(customer_id))  AS number_of_customers FROM customer_orders_temp;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/177/1*FMmYKeGcLZ-r4iaQHEgYkQ.png" /></figure><ul><li>5 different customers ordered 14 pcs pizzas.</li></ul><h4>3) How many successful orders were delivered by each runner?</h4><pre>SELECT runner_id,COUNT(order_id) AS total_order FROM runner_orders_temp<br>WHERE distance IS NOT NULL AND distance != 0 <br>GROUP BY runner_id<br>ORDER BY runner_id;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*vNMpYllcxrEiRS1AHGZDiQ.png" /></figure><ul><li>A total of 8 orders were successfully delivered by runners.</li></ul><h4>4. How many of each type of pizza was delivered?</h4><pre>SELECT p.pizza_name, COUNT(r.order_id) FROM runner_orders_temp AS r<br>JOIN customer_orders_temp AS c<br>ON r.order_id = c.order_id <br>JOIN pizza_runner.pizza_names AS p<br>ON c.pizza_id = p.pizza_id<br>WHERE r.distance != 0<br>GROUP BY p.pizza_name;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/195/1*cXS0xI8UmIuSKzLkiyeVOw.png" /></figure><ul><li>Meatlovers pizza was delivered 9 pcs.</li><li>Vegetarian pizza was delivered 3 pcs.</li></ul><p><strong>5. How many Vegetarian and Meatlovers were ordered by each customer?</strong></p><pre>SELECT c.customer_id, p.pizza_name, COUNT(c.order_id) FROM customer_orders_temp AS c<br>JOIN pizza_runner.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/301/1*VtA28f31GnL8UegKUipZmw.png" /></figure><p><strong>6. What was the maximum number of pizzas delivered in a single order?</strong></p><pre>SELECT c.order_id, COUNT(c.pizza_id) AS max_pizza FROM customer_orders_temp AS c<br>JOIN runner_orders_temp AS r<br>ON c.order_id = r.order_id<br>WHERE r.distance != 0<br>GROUP BY c.order_id<br>ORDER BY max_pizza DESC<br>LIMIT 1;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/195/1*cFBSlh04hNO8lsv8kg6YWA.png" /></figure><ul><li>The maximum number of pizzas delivered in a single order 3 pcs. The customer is a true pizza lover. :)</li></ul><p><strong>7. For each customer, how many delivered pizzas had at least 1 change, and how many had no changes?</strong></p><pre>SELECT c.customer_id,<br> SUM(CASE WHEN c.exclusions != ‘’ OR c.extras != ‘’ THEN 1 ELSE 0 END) AS yes_change,<br> SUM(CASE WHEN c.exclusions = ‘’ AND c.extras = ‘’ THEN 1 ELSE 0 END) AS no_change<br>FROM customer_orders_temp AS c<br>JOIN runner_orders_temp AS r<br> ON c.order_id = r.order_id<br>WHERE r.distance != 0<br>GROUP BY c.customer_id<br>ORDER BY c.customer_id;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*nqvpriglH0-4D_xawV421g.png" /></figure><ul><li>Customers 101 and 102 preferred the original version of pizzas.</li><li>Customers 103, 104, and 105 made at least one change in pizzas.</li></ul><p><strong>8 ) How many pizzas were delivered that had both exclusions and extras?</strong></p><pre>SELECT SUM( CASE WHEN c.exclusions != ‘’ AND c.extras != ‘’ THEN 1 ELSE 0 END) AS pizza_extras_exclusions<br>FROM customer_orders_temp AS c<br>JOIN runner_orders_temp AS r<br> ON c.order_id = r.order_id<br>WHERE r.distance != 0</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/160/1*tI9bB0IsXjSQdIRiTHSinQ.png" /></figure><ul><li>One pcs pizza delivered that had both exclusions and extras.</li></ul><h4>9. What was the total volume of pizzas ordered for each hour of the day?</h4><pre>SELECT date_part(‘hour’, order_time) AS hour_of_the_day , COUNT(pizza_id) AS pizza_count <br>FROM customer_orders_temp<br>GROUP BY hour_of_the_day <br>ORDER BY hour_of_the_day;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/1*RIUm7hWIfU4_laprDWDQwA.png" /></figure><p><strong>10. What was the volume of orders for each day of the week?</strong></p><pre>SELECT TO_CHAR(order_time , ‘Day’) AS day, count(order_id) AS total_pizzas<br>FROM customer_orders_temp <br>GROUP BY day<br>ORDER BY day;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/213/1*W1J7at1fDhCQt1VB0PMKVQ.png" /></figure><ul><li>The highest volume of pizza was ordered on Saturday and Wednesday.</li></ul><h3>B. Runner and Customer Experience</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*tNYx-8ZNAmPHFm81oBmzuw.jpeg" /></figure><p><strong>1. How many runners signed up for each 1 week period? (i.e. week starts </strong><strong>2021-01-01)</strong></p><pre>SELECT MIN(r.registration_date) AS week_start, COUNT(r.runner_id) AS runner_signup<br>FROM pizza_runner.runners AS r <br>WHERE &#39;20210101&#39; &lt;= r.registration_date<br>GROUP BY DATE_PART(&#39;week&#39;, r.registration_date)<br>ORDER BY week_start;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/233/1*qOo2Ia0CBmNXN-XmDShp7g.png" /></figure><p><strong>2. What was the average time in minutes it took for each runner to arrive at the Pizza Runner HQ to pickup the order?</strong></p><pre>SELECT r.runner_id,<br>ROUND(AVG(EXTRACT(epoch FROM(r.pickup_time- c.order_time))/60),2) <br>FROM customer_orders_temp AS c<br>JOIN runner_orders_temp AS r<br>ON c.order_id = r.order_id<br>WHERE r.distance != 0 <br>GROUP BY r.runner_id<br>ORDER BY r.runner_id;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/187/1*g1wG6THYOhWv-CGQHHFONg.png" /></figure><p><strong>3. Is there any relationship between the number of pizzas and how long the order takes to prepare?</strong></p><pre>WITH prepare_time_cte AS(<br> SELECT c.order_id,<br> COUNT(c.order_id) AS pizza_order,<br> ROUND(AVG(EXTRACT(epoch FROM (r.pickup_time- c.order_time))/60),2) AS prepare_time<br> FROM customer_orders_temp AS c<br> JOIN runner_orders_temp AS r<br> ON c.order_id = r.order_id<br> WHERE r.distance != 0 <br> GROUP BY c.order_id)</pre><pre>SELECT pizza_order,round(AVG(prepare_time),0) AS avg_prepare_time <br>FROM prepare_time_cte<br>GROUP BY pizza_order<br>ORDER BY pizza_order;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*hC8_t-76rCgebjdAAxqPRA.png" /></figure><ul><li>An order with 1 pizza takes 12 minute</li><li>An order with 2 pizzas takes 18 minutes, average of 9 minutes per pizza.</li><li>An order with 3 pizzas takes 29 minutes, almost average of 10 minutes per pizza.</li></ul><p>Maximum efficiency is to make two pizzas in one order.</p><p><strong>4. What was the average distance traveled for each customer?</strong></p><pre>SELECT c.customer_id, ROUND(AVG(r.distance)) AS avg_distance<br>FROM customer_orders_temp AS c<br>JOIN runner_orders_temp AS r<br>ON c.order_id = r.order_id<br>WHERE r.distance != 0 <br>GROUP BY c.customer_id<br>ORDER BY c.customer_id;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/1*cMH3NU6yXUbUUdqHUWAxSA.png" /></figure><ul><li>Customer 104 stays the nearest, and Customer 105 stays the furthest to Pizza Runner.</li></ul><p><strong>5. What was the difference between the longest and shortest delivery times for all orders?</strong></p><pre>SELECT (MAX(duration) — min(duration)) AS delivery_time_diff <br>FROM runner_orders_temp;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/126/1*lXCLJVEKVenabs2EqS-PZQ.png" /></figure><ul><li>Longest delivery time is 40 minutes, shortest delivery time is 10 minutes. The difference between is 30 minutes.</li></ul><p><strong>6. What was the average speed for each runner for each delivery and do you notice any trend for these values?</strong></p><pre>SELECT runner_id , order_id, ROUND(distance / duration * 60) AS avg_speed FROM runner_orders_temp<br>WHERE distance !=0<br>GROUP BY order_id, runner_id, avg_speed<br>ORDER BY runner_id, order_id;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/335/1*ymtgKZ3d2ignwq8OGrvXfw.png" /></figure><p>Average speed = distance(km) / duration(s)</p><ul><li>The average speed is between 38 km/s and 60 km/s for Runner 1.</li><li>The average speed is between 35 km/s and 94 km/s for Runner 2. 94 km/s value may be an outlier value.</li><li>The average speed is 40 km/s for Runner 3.</li></ul><p><strong>7. What is the successful delivery percentage for each runner?</strong></p><pre>SELECT runner_id,ROUND((100* SUM(CASE WHEN distance != 0 THEN 1 <br>ELSE 0 END) / COUNT(*))) AS success_percantage <br>FROM runner_orders_temp<br>GROUP BY runner_id<br>ORDER BY runner_id;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/230/1*Pho_Mx5VK1BG4RN-P540oA.png" /></figure><h3>C. Ingredient Optimisation</h3><blockquote><em>I am creating a new temporary table named “</em><strong><em>pizza_temp</em></strong><em>” by merging pizza related tables . I used this table when solving questions.</em></blockquote><pre>CREATE TEMP TABLE pizza_temp AS(<br> <br> WITH pizza_recipes_temp AS<br>(SELECT<br> pizza_id,<br> REGEXP_SPLIT_TO_TABLE(toppings, ‘[,\s]+’)::INTEGER AS topping_id<br>FROM pizza_runner.pizza_recipes )<br> <br>SELECT pr.pizza_id, pn.pizza_name, pr.topping_id, pt.topping_name<br>FROM pizza_recipes_temp AS pr<br>JOIN pizza_runner.pizza_names AS pn<br>ON pr.pizza_id = pn.pizza_id<br>JOIN pizza_runner.pizza_toppings AS pt<br>ON pr.topping_id = pt.topping_id<br>ORDER BY pn.pizza_name, pr.topping_id, pt.topping_name);</pre><pre>SELECT * FROM pizza_temp;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*VdaBVmdK_HAvVPjWpt9QcQ.png" /></figure><p><strong>1. What are the standard ingredients for each pizza?</strong></p><ul><li>The standard ingredients are Bacon, BBQ Store, Beef, Cheese, Chicken, Musrooms, Peperoni, Salami for Meatlovers pizza.</li><li>The standard ingredients are Cheese, Mushrooms, Onions, Peppers, Tomatoes, Tomato Sauce for Vegetarian pizza.</li></ul><p><strong>2. What was the most commonly added extra?</strong></p><pre>WITH extras_cte AS(<br>SELECT pizza_id,<br>REGEXP_SPLIT_TO_TABLE(extras, ‘[,\s]+’)::INTEGER AS extras FROM customer_orders_temp<br>WHERE extras !=’’) </pre><pre>SELECT extras ,COUNT(*) AS most_added_extra FROM extras_cte<br>GROUP BY extras<br>ORDER BY most_added_extra DESC<br>LIMIT 1 ;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/1*dA3dn4Yzo7AVBNZb5WJUZQ.png" /></figure><ul><li>The most commonly added extra was Bacon.</li></ul><p><strong>3. What was the most common exclusion?</strong></p><pre>WITH exclusion_cte AS(<br>SELECT pizza_id, <br>REGEXP_SPLIT_TO_TABLE(exclusions, &#39;[,\s]+&#39;)::INTEGER AS exclusions FROM customer_orders_temp<br>WHERE exclusions !=&#39;&#39;) </pre><pre>SELECT exclusions , COUNT(*) AS most_exclusion FROM exclusion_cte<br>GROUP BY exclusions<br>ORDER BY most_exclusion DESC<br>LIMIT 1 ;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/247/1*UeiGi3GOCC5vg40tOKnAEA.png" /></figure><ul><li>The most common exclusion was Cheese.</li></ul><p><strong>4. Generate an order item for each record in the </strong><strong>customers_orders table in the format of one of the following:</strong></p><ul><li><strong>Meat Lovers</strong></li><li><strong>Meat Lovers - Exclude Beef</strong></li><li><strong>Meat Lovers - Extra Bacon</strong></li><li><strong>Meat Lovers - Exclude Cheese, Bacon - Extra Mushroom, Peppers</strong></li></ul><p><strong>5. Generate an alphabetically ordered comma-separated ingredient list for each pizza order from the </strong><strong>customer_orders table and add a </strong><strong>2x in front of any relevant ingredients</strong></p><ul><li><strong>For example: </strong><strong>&quot;Meat Lovers: 2xBacon, Beef, ... , Salami&quot;</strong></li></ul><p><strong>6. What is the total quantity of each ingredient used in all delivered pizzas sorted by most frequent first?</strong></p><pre>SELECT p.topping_name, COUNT(p.topping_name) as ingredient_quantity FROM pizza_temp AS p<br>JOIN customer_orders_temp AS c<br>ON p.pizza_id = c.pizza_id <br>JOIN runner_orders_temp AS r<br>ON c.order_id = r.order_id<br>WHERE r.distance != 0<br>GROUP BY p.topping_name                                                                 <br>ORDER BY ingredient_quantity DESC;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/1*TamQVFN90Bh83nZ9LBwB0A.png" /></figure><ul><li>The total quantity of Cheese ingredient is 12 and is the most.</li></ul><h4><strong>D. Pricing and Ratings</strong></h4><p><strong>1.If a Meat Lovers pizza costs $12 and Vegetarian costs $10 and there were no charges for changes — how much money has Pizza Runner made so far if there are no delivery fees?</strong></p><pre>WITH prices AS(<br>SELECT p.pizza_name, CASE <br>WHEN p.pizza_name = ‘Meatlovers’ THEN 20 ELSE 10 END price<br>FROM pizza_runner.pizza_names AS p<br>JOIN customer_orders_temp AS c<br>ON p.pizza_id = c.pizza_id<br>JOIN runner_orders_temp AS r<br>ON r.order_id = c.order_id<br>WHERE r.distance != 0 )</pre><pre>SELECT SUM(price) AS total_prices FROM prices;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/126/1*gfAAlUxZAmevJ55vltXN9A.png" /></figure><ul><li>Pizza Runner has money 210 $.</li></ul><p>For your suggestions, you can reach me <a href="https://www.linkedin.com/in/emine-tolun/">here</a>. You can find all the codes <a href="https://github.com/eminetolun/8WeekSQLChallenge/blob/main/Case_Study2.sql">here</a>.</p><p>Thank you for reading. See you in the third case. :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8822566ec7d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[8 Weeks Challenge]]></title>
            <link>https://medium.com/@eminetolun/8-weeks-challenge-5d44c2e44f0e?source=rss-cab3d3c96832------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d44c2e44f0e</guid>
            <dc:creator><![CDATA[Emine Tolun]]></dc:creator>
            <pubDate>Wed, 13 Apr 2022 10:21:44 GMT</pubDate>
            <atom:updated>2022-05-24T18:29:06.159Z</atom:updated>
            <content:encoded><![CDATA[<h3>8 Weeks SQL Challenge: Case Study #1 -Danny’s Diner</h3><p>You can find this challenge <a href="https://8weeksqlchallenge.com/case-study-1/">here</a>. Thank you Danny Ma for the case study..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IjQ8XODW__ifjJqoBCvNVw.png" /></figure><h3>Introduction</h3><p>Danny seriously loves Japanese food so in 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 is in need of your assistance to help the restaurant stay afloat — the restaurant has captured some very basic data from their few months of operation but have no idea how to use their data to help them run the business.</p><h3>Problem Statement</h3><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 favourite. Having this deeper connection with his customers will help him deliver a better and more personalised 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>Danny has shared with you 3 key datasets 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.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*mzDLOlD0imXTPYKZQ7W1CQ.png" /><figcaption><strong>Entity-Relationship Diagram</strong></figcaption></figure><h3>Case Study Questions</h3><p>Each of the following case study questions can be answered using a single SQL statement:</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 are the total items and amount spent for 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’s start answering! :)</p><h3>Solutions</h3><p>I’m using PostgreSQL for all questions and answers.</p><ol><li><strong>What is the total amount each customer spent at the restaurant?</strong></li></ol><pre>SELECT s.customer_id , SUM(price) AS total_amount <br>FROM db.sales AS s<br>LEFT JOIN db.menu m ON s.product_id = m.product_id<br>GROUP BY customer_id<br>ORDER BY customer_id;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/279/1*kJ-gv0lxj6s4Qyji37_1WQ.png" /></figure><ul><li>Total amounts of A,B,C customers are $76, $74, $36.</li></ul><p><strong>2. How many days has each customer visited the restaurant?</strong></p><p>The DISTINCT function was used to avoid repeating the number of days.</p><pre>SELECT customer_id , COUNT(DISTINCT(order_date)) AS number_of_visits  FROM db.sales<br>GROUP BY customer_id<br>ORDER BY customer_id;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/271/1*D_gah6-sh7cO7Va3-qdEgA.png" /></figure><ul><li>The number of visits of A, B and C customers are 4, 6 and 2 times.</li></ul><p><strong>3. What was the first item from the menu purchased by each customer?</strong></p><p>We create the temporary table product_cte using WITH function.</p><p>A customer may have ordered two or more orders on the same date because the date is not time-tagged. That’s why DENSE_RANK function used.</p><pre>WITH product_cte AS(<br>SELECT customer_id, product_id, DENSE_RANK() OVER (PARTITION BY customer_id ORDER BY order_date) AS ranking<br>FROM db.sales)<br>SELECT c.customer_id, m.product_name<br>FROM product_cte c<br>JOIN db.menu m on c.product_id=m.product_id<br>WHERE ranking = 1<br>ORDER BY c.customer_id;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*y3eCd0A3xTA8APBOjnbsog.png" /></figure><ul><li>The first orders of Customer A are curry and sushi.</li><li>The first order of Customer B is curry.</li><li>The first order of Customer B is ramen.</li></ul><p><strong>4. What is the most purchased item on the menu and how many times was it purchased by all customers?</strong></p><p>MENU and SALES tables merge using JOIN function.</p><pre>SELECT product_name, COUNT(s.product_id) AS most_purchased <br>FROM db.sales s <br>JOIN db.menu m <br>ON s.product_id = m.product_id<br>GROUP BY product_name<br>ORDER BY most_purchased DESC<br>LIMIT 1;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*QcpkOOvXeXXzWiPQEIS3jQ.png" /></figure><p>The most purchased item on the menu is ramen. Ramen was purchased 8 times.</p><p><strong>5. Which item was the most popular for each customer?</strong></p><p>Created two temporary tables with WITH function.</p><pre>WITH CustomerProduct AS (<br>  SELECT s.customer_id ,product_id, COUNT(s.product_id) AS items <br>  FROM db.sales s<br>  GROUP BY customer_id, product_id<br>) <br>, CustomerProductRanking AS (<br> SELECT c.customer_id , m.product_name, c.items, DENSE_RANK() OVER (PARTITION BY customer_id ORDER BY c.items ) AS ranking <br> FROM CustomerProduct c<br> JOIN db.menu m <br> ON c.product_id = m.product_id)</pre><pre>SELECT customer_id , product_name FROM CustomerProductRanking <br>WHERE ranking = 1 ;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/1*qrQiNa4NVcqXHMLbTerc-Q.png" /></figure><ul><li>The most popular item for Customer A was sushi.</li><li>The most popular items for Customer B were curry, sushi, and ramen.</li><li>The mod popular item for Customer C was ramen.</li></ul><p><strong>6. Which item was purchased first by the customer after they became a member?</strong></p><pre>WITH ProductDate AS(<br> SELECT s.customer_id, m.join_date, s.order_date, s.product_id, DENSE_RANK() OVER(PARTITION BY s.customer_id ORDER BY s.order_date) AS ranking<br> FROM db.sales s<br> JOIN db.members m<br> ON s.customer_id = m.customer_id WHERE s.order_date &gt;= m.join_date<br>) <br>SELECT p.customer_id ,p.join_date, p.order_date, menu.product_name <br>FROM ProductDate p<br>JOIN menu<br>ON p.product_id = menu.product_id<br>WHERE ranking = 1<br>ORDER BY customer_id;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/1*uh8ftb_J2JVhi_hooCYF3Q.png" /></figure><ul><li>Customer A purchased the first curry on the day becoming a member.</li><li>Customer B purchased the first curry 2 days after becoming a member.</li><li>Customer C isn’t yet a member.</li></ul><p><strong>7. Which item was purchased just before the customer became a member?</strong></p><pre>WITH ProductDate AS(<br> SELECT s.customer_id, s.order_date, s.product_id, DENSE_RANK() OVER(PARTITION BY s.customer_id ORDER BY s.order_date) ranking<br> FROM db.sales s<br> JOIN db.members m<br> ON s.customer_id = m.customer_id<br> WHERE s.order_date &lt; m.join_date<br>) <br>SELECT p.customer_id , p.order_date, menu.product_name  <br>FROM ProductDate p<br>JOIN menu<br>ON p.product_id = menu.product_id<br>WHERE ranking = 1<br>ORDER BY customer_id ;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*QFt3NoZbCNZKZe_raaNQXA.png" /></figure><p><strong>8. What are the total items and amount spent for each member before they became a member?</strong></p><pre>SELECT s.customer_id, COUNT(m.product_name) product_count, SUM(m.price) total_price <br>FROM db.sales s<br>JOIN db.members mb<br>ON s.customer_id = mb.customer_id<br>JOIN db.menu m<br>ON s.product_id = m.product_id<br>WHERE s.order_date &lt; mb.join_date<br>GROUP BY s.customer_id;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*3OuXq5F8LmfxUcGRLlIgkg.png" /></figure><p>Before becoming members,</p><ul><li>Customer A spent $ 25 on 2 items.</li><li>Customer B spent $40 on 3 items.</li></ul><p><strong>9. If each $1 spent equates to 10 points and sushi has a 2x points multiplier — how many points would each customer have?</strong></p><p>Each $1 spent = 10 points.</p><p>But each $1 spent = 2 x 10 points for sushi . That’s why we use CASE WHEN.</p><pre>WITH points AS (<br> SELECT product_id, product_name,<br> CASE <br> WHEN m.product_id =1 THEN price * 20<br> ELSE price * 10<br> END points<br> FROM db.menu m<br>)<br>SELECT customer_id, SUM(p.points) total_points <br>FROM db.sales s<br>JOIN points p<br>ON s.product_id = p.product_id <br>GROUP BY customer_id<br>ORDER BY customer_id;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/269/1*OvIDSLbEucBmG53ZE56glw.png" /></figure><ul><li>Total points for Customers A, B, and C are 860, 940, and 360.</li></ul><p><strong>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?</strong></p><pre>CREATE FUNCTION end_of_month(date)<br>RETURNS date AS<br>$$<br>SELECT (date_trunc(‘month’, $1) + interval ‘1 month’ — interval ‘1 day’)::date;<br>$$ LANGUAGE ‘sql’<br>IMMUTABLE STRICT;</pre><p><em>Creating a function called end_of_month to find the last day of the month.</em></p><pre>WITH dates_cte AS(<br> SELECT s.customer_id ,m.product_name, s.order_date, mb.join_date, mb.join_date + integer ‘6’ as valid_date, end_of_month(mb.join_date) as end_of_month, m.price<br> FROM db.members mb<br> JOIN db.sales s<br> ON mb.customer_id = s.customer_id<br> JOIN db.menu m <br> ON s.product_id = m.product_id <br>)<br>SELECT d.customer_id, d.product_name, <br>SUM(<br> CASE<br> WHEN d.product_name = ‘sushi’ THEN d.price * 2*10 <br> WHEN d.order_date BETWEEN d.join_date AND d.valid_date THEN d.price * 2 * 10 <br> ELSE d.price * 10 END<br>) AS total_points <br>FROM date_cte d<br>WHERE d.order_date &lt; d.end_of_month<br>GROUP BY d.customer_id , d.product_name ;</pre><p>valid_date: Date of in the first week after a customer joins the program</p><p>end_of_month: Last date of the month</p><ul><li>Between join_date and valid_date, each $1 spent on all items is 20 points.</li><li>Between valid_date and end_of_month, each $1 spent on all items is 10 points, not just sushi. Each $1 spent always is 20 points for sushi.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*Bq61IO9JH2XbNNEfw2pRdg.png" /></figure><ul><li>Total points of Customer A is 1370.</li><li>Total points of Customer B is 820.</li></ul><h4>BONUS QUESTIONS</h4><h4>Join All The Things</h4><p>Creating a table again with customer_id, order_date, product_id, price, member.</p><pre>SELECT s.customer_id, s.order_date, s.product_id, m.product_name, m.price,<br>CASE <br>WHEN mb.join_date &gt; s.order_date THEN ‘N’<br>WHEN mb.join_date &lt;= s.order_date THEN ‘Y’<br>ELSE ’N’ <br>END member<br>FROM db.sales s<br>LEFT JOIN db.members mb<br>ON s.customer_id = mb.customer_id<br>JOIN db.menu m<br>ON s.product_id = m.product_id;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*-vk-FsENthfxS5X5jQsASQ.png" /></figure><h4>Rank All The Things</h4><p>Danny also requires further information about the ranking of customer products, but he purposely does not need the ranking for non-member purchases so he expects null ranking values for the records when customers are not yet part of the loyalty program.</p><pre>WITH all_cte AS(<br> SELECT s.customer_id, s.order_date, s.product_id, m.product_name, m.price,<br> CASE <br> WHEN mb.join_date &gt; s.order_date THEN ‘N’<br> WHEN mb.join_date &lt;= s.order_date THEN ‘Y’<br> ELSE ’N’ END member<br> FROM db.sales s</pre><pre>LEFT JOIN db.members mb<br>ON s.customer_id = mb.customer_id<br>JOIN db.menu m<br>ON s.product_id = m.product_id)<br>SELECT * , <br>CASE<br>WHEN member = ‘Y’ THEN RANK() OVER(PARTITION BY customer_id, member ORDER BY order_date ) <br>ELSE NULL<br>END AS ranking<br>FROM all_cte;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*P6_G2ZaZlNtmCNRg8BSu8g.png" /></figure><p>For your suggestions, you can reach me <a href="https://www.linkedin.com/in/emine-tolun/">here</a>. You can find all the codes <a href="https://github.com/eminetolun/8WeekSQLChallenge">here</a>.</p><p>Thank you for reading. See you in the second case. :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d44c2e44f0e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>