<?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 Alfiramdhan on Medium]]></title>
        <description><![CDATA[Stories by Alfiramdhan on Medium]]></description>
        <link>https://medium.com/@alfiramdhan?source=rss-82c640d9f481------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ydvt_ilCRKr2m-VLsSM7lQ.png</url>
            <title>Stories by Alfiramdhan on Medium</title>
            <link>https://medium.com/@alfiramdhan?source=rss-82c640d9f481------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 08:22:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alfiramdhan/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[Customer Segmentation Analysis : Uncovering Buyer and Seller Segments for Strategic Success]]></title>
            <link>https://medium.com/@alfiramdhan/customer-segmentation-analysis-uncovering-buyer-and-seller-segments-for-strategic-success-ab8b88db4383?source=rss-82c640d9f481------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab8b88db4383</guid>
            <category><![CDATA[k-means-clustering]]></category>
            <category><![CDATA[clustering]]></category>
            <category><![CDATA[customer-segmentation]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Alfiramdhan]]></dc:creator>
            <pubDate>Thu, 28 Dec 2023 04:58:12 GMT</pubDate>
            <atom:updated>2023-12-28T04:58:12.462Z</atom:updated>
            <content:encoded><![CDATA[<h3>Customer Segmentation Analysis : Uncovering Buyer and Seller Segments for Strategic Success</h3><p><em>Disclaimer : The data provided is a representation of the original data which amount has been adjusted. The dataset that is used for this presentation has been cleaned, so the process of merging, removing unnecessary columns, typos and nulls has been done prior to this.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UOyJtJrlH4Z72Uu9" /><figcaption>Photo by <a href="https://unsplash.com/@blakewisz?utm_source=medium&amp;utm_medium=referral">Blake Wisz</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Understanding how customers behave is important for businesses. It helps improve profits by creating, pricing, and promoting products that meet customer expectations. It also helps identify target audiences and develop strategies to keep customers coming back. Therefore, it’s crucial for businesses to understand customer behaviors and create strategies focused on customers.</p><p>In this virtual internship project by <a href="https://revou.co/">RevoU</a> x <a href="https://www.telkom.co.id/sites">Telkom Indonesia</a>, my goal is to segment customers using RFM metrics and KMeans clustering methods. By doing so, we can enhance marketing strategies and make campaigns more effective. To analyze the data, I will extract the dataset using Google BigQuery. Then, I’ll utilize Google Colab to transform the data, segment it, and create visualizations using Loker Studio.</p><p>The dataset I am working with contains information about the number of transactions in a marketplace (e-commerce) initiated by the Ministry of BUMN, the Ministry of UMKM, and the LKPP (Lembaga Kebijakan Pengadaan Barang/Jasa Pemerintah) during the year 2022.</p><p><strong><em>Now, Let’s get started!</em></strong></p><p>First of all, since we are using the e-commerce dataset, let’s review the features of the dataset:</p><ul><li>The dataset includes sales data of an online marketplace during 2022.</li><li>There are 29 different columns in the dataset. These are: ‘transaction_date’, ‘po_number’, ‘order_id’, ‘order_status’, ‘payment_group’, ‘shipping_agency’, ‘shipping_cost’, ‘total_project_value’, ‘revenue’, ‘seller_id’, ‘seller_category’, ‘buyer_id’, ‘seller_province’, ‘seller_city’, ‘seller_flag’, ‘buyer_province’, ‘buyer_city’, ‘buyer_flag’, ‘product_id’, ‘product_name’, ‘main_cat’, ‘brand’, ‘price_per_item’, ‘quantity’, ‘price_total’, ‘free_shipping’, ‘ppn’, ‘weight_total’, ‘unit’ columns.</li><li>There are 474,570 rows in the dataset.</li><li>Customer-based analysis can be done with the customer IDs in the data set (seller_id, buyer_id).</li></ul><h3>Clustering</h3><p>Clustering is a machine learning technique that helps us group similar objects together and categorize dissimilar objects into different groups.</p><p>In this project, I use two widely used clustering approaches: K-Means Clustering and Hierarchical Clustering to create customer segmentation.</p><p>The analysis of the customers in the data set with RFM metrics and clustering methods was performed as follows:</p><pre>from sklearn.cluster import KMeans<br>from sklearn.preprocessing import MinMaxScaler<br>from sklearn.preprocessing import StandardScaler<br>from sklearn.preprocessing import RobustScaler<br>from sklearn import cluster<br>from yellowbrick.cluster import SilhouetteVisualizer<br>import warnings<br>warnings.filterwarnings(&quot;ignore&quot;, category=FutureWarning)<br><br>from datetime import datetime<br>from sklearn.cluster import KMeans<br>import matplotlib.pyplot as plt<br>from sklearn.preprocessing import StandardScaler<br><br>trans.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tvcAwnrj6yQHQnv1.png" /></figure><p>Since the focus is only on three variables, all you need are three data points:</p><ol><li>Current (Last) Order Date: This represents the most recent order date for a seller or customer. It indicates how recently they made a purchase.</li><li>Frequency: This metric denotes the total number of orders made by a seller or customer. It reveals their ordering frequency and helps identify those who make repeat purchases.</li><li>Monetary Value: This metric represents the total revenue generated by a seller or customer. It shows their contribution to the overall revenue and highlights those who generate the most revenue.</li></ol><p>By analyzing these three metrics, you can gain insights into sellers who have repeat sales, customers who demonstrate long-term loyalty, and customers who contribute significantly to the revenue.</p><pre>from datetime import datetime<br>from sklearn.cluster import KMeans<br>import matplotlib.pyplot as plt<br>from sklearn.preprocessing import StandardScaler<br><br>pd.set_option(&#39;display.max_columns&#39;, None)<br>pd.set_option(&#39;display.float_format&#39;, lambda x: &#39;%.2f&#39; % x)<br>pd.set_option(&#39;display.width&#39;, 500)</pre><pre>snapshot_date = trans[&#39;transaction_date&#39;].max() + pd.DateOffset(days=1)<br>rfm_df = trans.groupby([&#39;seller_id&#39;]).agg({<br>    &#39;transaction_date&#39;: lambda x: (snapshot_date - x.max()).days,<br>    &#39;order_id&#39;: &#39;count&#39;,<br>    &#39;revenue&#39;: &#39;sum&#39;})<br>print(rfm_df)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5I7kN706xpgnC0Ap" /></figure><p>Renaming columns :</p><pre>rfm_df.rename(columns={&#39;transaction_date&#39;: &#39;Recency&#39;,<br>                        &#39;order_id&#39;: &#39;Frequency&#39;,<br>                        &#39;revenue&#39;: &#39;MonetaryValue&#39;}, inplace=True)<br>print(rfm_df)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CZk8K9BGK5NCejIi.png" /></figure><h3>Applying Clustering Method :</h3><p>In this project, I think <strong>K-Means Clustering seems to give better results than Hierarchical Clustering</strong>. Hierarchical Clustering has <strong>more intersections or intersections between clusters compared to K-Means.</strong> Following are the visualization results:</p><h3>K-Means Clustering</h3><p>K-means is an iterative algorithm that aims to partition data into K clusters so that each observation belongs to only one of the K clusters. The objective is to have a minimal “with-cluster-variation”, i.e., the elements in the same cluster should be as similar as possible.</p><p><strong>The K-Means </strong>clustering algorithm was applied using the Recency, Frequency, MonetaryValue. Then three variables in the dataset are selected and assigned to variable X. The data is then normalized so that the data can be compared with each other. This is done through a Standardization process. Then using the K-Means algorithm, the data is divided into three different clustering groups.</p><p>I chose the number of clusters, k=3 to categorize and randomly selected K data points as centroids (cluster centers) of each cluster.</p><pre>X = rfm_df[[&#39;Recency_Months&#39;, &#39;Frequency&#39;, &#39;Monetary&#39;]]<br>scaler = StandardScaler()<br>X_scaled = scaler.fit_transform(X)<br>kmeans = KMeans(n_clusters=3)<br>kmeans.fit(X_scaled)<br>rfm_df[&#39;cluster&#39;] = kmeans.labels_</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HWO369PgGqwcSdWj" /><figcaption>Customer cluster using the K-Means method</figcaption></figure><h3>Hierarchical Clustering</h3><p>Unlike the K-Means algorithm, the hierarchical algorithm does not require a representative for each cluster. Instead, It assumes that the clusters are hierarchically structured. That is, every cluster is made up of some smaller clusters.</p><p>Even though the hierarchical clustering algorithm doesn’t need to define the number of clusters in advance, we still need to decide the number of clusters for data analysis. To get the number of clusters for hierarchical clustering, we make use of Dendrogram which is a tree-like diagram that records the sequences of merges or splits.</p><p>In this project,</p><pre>cluster_labels = model.fit_predict(hie_seller)<br>cluster_labels<br><br>linkage_matrix = hierarchy.linkage(model.children_)<br>linkage_matrix[:][:5]<br><br>plt.figure(figsize=(30,10))<br>hierarchy.set_link_color_palette([&#39;r&#39;,&#39;grey&#39;, &#39;b&#39;, &#39;grey&#39;, &#39;m&#39;, &#39;grey&#39;, &#39;g&#39;, &#39;grey&#39;, &#39;orange&#39;]) # set colors for the clusters<br>dn = hierarchy.dendrogram(linkage_matrix,truncate_mode=&#39;level&#39;,p=15, color_threshold=23) # color_threshold=23 sets clusters below y-axis value of 23 to be of the same color</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*b2UbUSfcpNZnUmcK.png" /><figcaption>The Dendogram</figcaption></figure><pre>model = AgglomerativeClustering(n_clusters=3)<br>hie_seller[&#39;cluster&#39;]=model.fit_predict(hie_seller) # predict the categories for each point.<br><br># create a scatter plot of the data with different colors for each cluster<br>sns.scatterplot(x=&#39;Recency&#39;, y=&#39;Frequency&#39;, hue=&#39;cluster&#39;, data=hie_seller, palette=&quot;deep&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/0*v8flfX96cqhgVsnp.png" /><figcaption>Customer cluster using the Hierarchical method</figcaption></figure><p>In this project, I tried to compare the K-Means algorithm and the hierarchical algorithm to get the best cluster. As we can see that K-Means Clustering seems to give better results than Hierarchical Clustering. Hierarchical Clustering has more intersections or intersections between clusters compared to K-Means. K-Means clustering is faster and simpler, but requires choosing the number of clusters beforehand. On the other hand, hierarchical clustering is more flexible and intuitive, but can be computationally expensive and sensitive to outliers.</p><p>When examining the resulting graph of K-Means clustering, we observe different groups represented by dots of different colors. For instance, the blue dots might show customers with the most recent transaction some time ago and resulting in the lowest number of transactions. On the other hand, red dots may represent customers with a medium frequency pattern and a medium revenue pattern. Yellow dots can represent customers who made the highest purchases (frequency) and most recent transactions.</p><p>By utilizing this chart, businesses can segment their customers into distinct groups and devise strategies that cater to the specific needs of each customer segment. For example, they can provide them with exclusive benefits such as early access to new products to high-frequency and high-sales customers to enhance their loyalty. Additionally, they can develop targeted offers or personalized marketing campaigns to re-engage customers who make infrequent purchases.</p><p><strong><em>Now let’s evaluate the value of K!</em></strong></p><h3>Elbow Method</h3><p>The main idea of this method is to calculate the sum of the squared distance between each data point and the centroid within a cluster for different values of K, this value is also called Within-Cluster-Sum of Squared Errors (WCSS).</p><p>Based on the cluster results above, it is necessary to evaluate and find the value of K. There are several potential “elbow” points on the plot here: perhaps k=3 or k=4 , which are inflection points where the rate of decline of WCSS slows down significantly. To be more certain, we also need to look at the silhouette plot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mQMUnr0lfIjqTIyU" /></figure><h3>Silhouette</h3><p>The value range of the Silhouette coefficient/score is between -1 to 1.</p><ul><li>1: Means clusters are well apart from each other and clearly distinguished.</li><li>0: Means clusters are indifferent, or we can say that the distance between clusters is not significant.</li><li>-1: Means clusters are assigned in the wrong way.</li></ul><p>So we need to find a k value that can get the Silhouette score most close to 1.</p><p>Based on the average silhouette score below, K=3 has the highest silhouette score among all candidates. So we can conclude that 3 clusters is right to proceed.</p><ul><li>For k=3, the average silhouette score is 0.9492420153401037</li><li>For k=4, the average silhouette score is 0.9054663447319926</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/0*L13zSosIDwSh1hrA" /></figure><h3>Interpretation the result for Sellers</h3><p>The table below shows average of each variables.</p><ul><li>Recency (R) : days since last transaction</li><li>Frequency (F) : total number of transaction</li><li>Monetary (M) : average of revenue</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/0*58do2XSp2hqcMAj2" /></figure><p>The result on the side shows that these variables <strong>unique enough that each cluster shows a different behavior</strong>.</p><ul><li>Cluster 0 : Transaction quite some time ago, the lowest #transaction, generated the lowest revenue</li><li>Cluster 1 : Recent transactions, #midtransactions, mid-revenue</li><li>Cluster 2 : Newest, highest #transactions, highest revenue</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8Hqum5YqDQlwhVr4.png" /><figcaption>Cluster of Sellers</figcaption></figure><h3>Interpretation the result for Buyers</h3><p>The table below shows average of each variables.</p><ul><li>Recency (R) : days since last transaction</li><li>Frequency (F) : total number of transaction</li><li>Monetary (M) : average of revenue</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/0*H0YxYy-WS7jVVxIh" /></figure><p>The result on the side shows that these variables <strong>unique enough that each cluster shows a different behavior</strong>.</p><ul><li>Cluster 0 : Recent transactions, #midtransactions, mid-revenue</li><li>Cluster 1 : Transaction quite some time ago, the lowest #transaction, generated the lowest revenue</li><li>Cluster 2 : Newest, highest #transactions, highest revenue</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YbJjlo8gcdNcBpJk.png" /></figure><p><strong><em>Here’s the detail code in </em></strong><a href="https://colab.research.google.com/drive/1NIN4JenJYGFsQ3nptHccRqZWCZT5b30d?usp=sharing"><strong><em>Google Colab!</em></strong></a></p><p>Those are the Results of Customer Segmentation Using the K-Means Method!! You can create as many clustering variables as you want.</p><p>Hope you all have a fruitful Data Analytics journey! Have a nice day~</p><p>If you want to see more details regarding this project, you can follow me on the following platforms.</p><p><a href="https://www.linkedin.com/in/alfianaramdhan/"><strong>https://www.linkedin.com/in/alfianaramdhan/</strong></a><strong><br></strong><a href="https://github.com/alfiramdhan/Customer-Segmentation-Analysis/blob/main/README.md"><strong>https://github.com/alfiramdhan/</strong></a></p><p>#kmeans #clustering #customersegmentation #dataanalysis #dataanalytics #sql #python</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab8b88db4383" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Applying Data Visualization to Monitor 2021 Business Growth]]></title>
            <link>https://medium.com/@alfiramdhan/applying-data-visualization-to-monitor-2021-business-growth-3fba9fd23c0d?source=rss-82c640d9f481------2</link>
            <guid isPermaLink="false">https://medium.com/p/3fba9fd23c0d</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[dashboard]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[tableau]]></category>
            <dc:creator><![CDATA[Alfiramdhan]]></dc:creator>
            <pubDate>Mon, 25 Sep 2023 04:33:59 GMT</pubDate>
            <atom:updated>2023-09-25T04:33:59.122Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Create a dashboard in Tableau to monitor a number of internal and external variables that support business growth</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2MXPvrZ_dc67v6a7fGop1Q.png" /></figure><p>Data visualization is not only useful for us to understand the data, but also to present the insights of the data in the form of a graphical representation which is much easier to understand.</p><p>Let’s say we work as Data Analysts and the CEO asks to create a company-wide dashboard.</p><p>So, how do you create the right dashboard for a CEO?</p><h3>Background</h3><p><strong>Samba commerce</strong> is one of the fast growing e-commerce in Brazil, which was just <strong>launched in 2021</strong>. Samba offers more than <strong>15k products</strong> and more than <strong>50 product categories</strong> to customers all over Brazil.</p><p>The company wants to <strong>monitor</strong> a number of internal and external variables that support the <strong>business growth</strong>. And the expected outcome is <strong>a Company-wide Dashboard</strong> that could,</p><ul><li>Show chart for analysis of company-wide to understand our business performance</li><li>Capture and understand more metrics and make the data more to be more comprehensive and insightful</li></ul><h3>Data Overview</h3><p>In this project, I used some tables from Samba commerce, to create graphs including:</p><ul><li>Order : 49544 rows x 10 columns</li><li>Order History : 49544 rows x 5 columns</li><li>Payment : 49544 rows x 4 columns</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*6jvwhuYvkyPoSyqq3SdU4g.png" /></figure><p>I use <strong>Relationships</strong> to combine data for multi-table analysis because it makes data preparation and <strong>analysis easier</strong> and more intuitive.</p><p>For Relationships, the data tables that get dragged onto the logical layer remain <strong>distinct and not merged in the data</strong>, connected by flexible noodles.</p><h3>Retrospective</h3><p>Let’s look back to what we have achieved!</p><p><a href="https://public.tableau.com/views/W10W11_alfiana_ramdhan_intermediate/SambaDashboard?:language=en-GB&amp;:display_count=n&amp;:origin=viz_share_link"><em>Click here to the Tableau Dashboard!</em></a></p><p>In a year period, from Jan 2021, <strong>the number of customers, sellers and orders has increased significantly</strong>. But the average customer <strong>only buys 1 unique item</strong>. We can conclude that our customer is only <strong>shopped in our commerce once</strong> and have not been coming back.We have a problem to focus our customers to buy more.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XE2a_QNrjPH0e86k6OGY7Q.png" /></figure><h4><strong>Monthly Order vs Total Payment Value</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*QIymfJXV35DPSuFNc9jHMQ.png" /></figure><ul><li>Monthly orders and total payment values, both have an <strong>upward trend</strong> and have continued to increase throughout the month for the <strong>last 1 year</strong></li><li>The trend <strong>peaked</strong> at November 2021</li><li>We <strong>need to further analysis</strong> what event/strategy happened/done on that month to gather insights on what made our customers want to shop more</li></ul><h4>Customers vs Seller</h4><p>As we can see, the majority of our customers, sellers and orders are very concentrated in state SP, specifically in Sao Paulo. Our top seller by order are also coming from state SP, meaning we can focus on this state first before expanding to other state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2-PHITEhg6UzK0mTBpIOTQ.png" /></figure><h4>Average Order Value Trend</h4><p>Our AOV trend is also <strong>decreasing 9%</strong> that also need to further analysis. This downtrend indicates that we may have acquired customers that have less spending power</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BNibfORPbWmnR6b6YpD8ng.png" /></figure><h4>Average Unique Items per Customer</h4><p>The trend of avg unique items per customer are decreasing and by the proportion 44k from 48k (91%) of our customers only ever bought 1 item. So we need to push our customer to buy more.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xHo0oc-2vhJ5tzgFYv3jTg.png" /></figure><p>P.S : this project was part of my assignment at <a href="https://revou.co/">RevoU</a> during my bootcamp</p><p><em>I hope you enjoyed this article, thank you for reading!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3fba9fd23c0d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Utilization of SQL Logical Operators For Company Marketing Strategy]]></title>
            <link>https://medium.com/@alfiramdhan/utilization-of-sql-logical-operators-for-sales-analysis-reports-8178ca47728a?source=rss-82c640d9f481------2</link>
            <guid isPermaLink="false">https://medium.com/p/8178ca47728a</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[portfolio]]></category>
            <category><![CDATA[sql-functions]]></category>
            <dc:creator><![CDATA[Alfiramdhan]]></dc:creator>
            <pubDate>Sun, 22 Jan 2023 11:14:21 GMT</pubDate>
            <atom:updated>2023-01-23T08:19:49.809Z</atom:updated>
            <content:encoded><![CDATA[<p>How to implement Boolean data types, logical operators, use of logical operators for filtering, and create new variables in e-commerce companies</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*Yt-Bv_XTFp9YrIPhPziWrQ.jpeg" /></figure><p>Hi everyone!!</p><p>On this occasion, I will try to share knowledge from a series of SQL lessons that I got from the <a href="https://academy.dqlab.id/main/">DQLab</a> learning platform.</p><p>Let’s say I work as a Data Analyst at DQ-Shop and am placed in the internet marketing division. My job is to optimize DQ-Shop’s marketing strategy. As it was already November, the team leader wanted a sales report as material for consideration for stock preparation for each type of item to be sold in the coming month. In addition, they will give discount vouchers to customers to use during <em>year-end</em> sales.</p><p>So, how do I prepare for the <em>year-end</em> sale program?</p><p><strong><em>Let’s get started!</em></strong></p><h3><strong>1.</strong> <strong>Project Background</strong></h3><p>DQ-Shop is a company engaged in the fashion sector. Every November, DQ-Shop usually starts preparing for the <em>year-end</em> sale program. That’s a pretty big discount offer program for the month of December.</p><p>This <em>year-end</em> sale program will run in four weeks. The first three weeks, the Data Analyst will focus on <strong>providing vouchers and marketing programs to notify customers via email</strong>. In addition, the Data Analyst must <strong>also create a DQ-Shop sales report</strong> to prepare the stock of goods to be sold.</p><p><em>Note: All questions are written in the code editor available at </em><a href="https://academy.dqlab.id/main"><strong><em>https://academy.dqlab.id/main/</em></strong><em>.</em></a></p><h3><strong>2.</strong> <strong>Data Preparation</strong></h3><h4><strong>2.1</strong> <strong>Tables</strong></h4><p>This project was provided by <a href="https://academy.dqlab.id/main">DQLab</a> so the dataset I’m using comes from that platform. The following dataset is named summary_transaction with 100,000 rows and consists of column customer_id of the customer who made the transaction, product details, first_transaction total purchases, last_transaction total purchases, average_transaction and count_transaction.</p><p>Here’s the table :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5No1Y4yW_qK8uSkC9HFUBw.png" /></figure><h3><strong>3.</strong> <strong>Project Goal</strong></h3><p>The Internet Marketing team needs your help to prepare data for <em>year-end</em> sale program.</p><p>Here are the details of the data that I have to prepare:</p><ol><li>Customer data (<strong>customer id</strong>) with an <strong>average purchase of more than IDR 1,000,000 per product</strong> will be entitled to get a shopping discount at the year-end sale.</li><li>Customers will be sent email marketing based on their total transactions. This email marketing will be divided based on <strong>historical data from the product purchased</strong>.</li><li>For the implementation of the year-end sale in the fourth week, sales data in the form of <strong>the average number of transactions (in rupiah) and the number of products sold</strong> are needed to prepare the stock of goods to be sold.</li><li>When the year-end sale project was running, the Team Leader got the idea to hold a lucky draw. DQ-Shop will distribute prizes in the form of shopping vouchers with the following conditions:</li></ol><ul><li>Two shopping vouchers of 1 million rupiah for lucky customers. Customers who are entitled to take part in this raffle are <strong>customers who have shopped at 3 different products and the average purchase of these three products or more is more than IDR 1,500,000.-.</strong></li><li><strong>Other customers outside the criteria (1)</strong> have the right to take part in a raffle of 3 shopping vouchers of 500 thousand rupiah for lucky customers.</li></ul><h3>4. <strong>Data Analysis</strong></h3><p>Q1. Customer data (<strong>customer id</strong>) with an <strong>average purchase of more than IDR 1,000,000 per product</strong> will be entitled to get a shopping discount at the year-end sale.</p><p>The discount voucher program that I’m working on will use the Boolean data type. The principle that I can use is that customers with an average purchase of at least IDR 1,000,000 will be given a value of 1 whereas if the average purchase is less than IDR 1,000,000 it will be worth 0.</p><p>Boolean is a data type that can be true or false and can be symbolized by 1 or 0. In this project, I will use MySQL server which actually doesn’t know the Boolean data type, but we can still use other data types to replace Boolean data.</p><p>We can create a new variable, namely <strong>‘is eligible’</strong>, when the average customer transaction per product is more than one million, it will have a value of 1 and a value of 0 when the average transaction is less than one million.</p><pre>SELECT DISTINCT Customer_ID,<br>        Product,<br>        Average_transaction,<br>        Average_transaction &gt;= 1000000 is_eligible<br>FROM summary_transaction;</pre><p>Result :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_izlcSVJXy0R6tIA3aCYQA.png" /></figure><p>The existing data can be used for the next process, namely data filtering. You do this by selecting ‘is eligible’ = 1 in the where command to get a list of customers who are entitled to a discount.</p><p>Q2. In addition to giving discount vouchers, DQ-Shop will send emails to customers to promote the year-end sales program and provide discount voucher codes using the data that I have prepared.</p><p>To attract customer attention, <strong>the marketing team will send 4–5 emails a week</strong> to customers <strong>with an</strong> <strong>average transaction of less than 1,000,000</strong>. Loyal customers with <strong>an average transaction of more than 1,000,000 will be sent 1–2 emails a week</strong> along with a discount voucher code.</p><p>I can use SQL logical functions and combine them with the case when command to do filtering and adding categories to the data.</p><pre>SELECT DISTINCT Customer_ID,<br>        Product,<br>        Average_transaction,<br>        Count_Transaction,<br>    CASE WHEN Average_transaction &lt; 1000000 then &#39;4-5x Email dalam seminggu&#39;<br>          WHEN Average_transaction &gt; 1000000 then &#39;1-2x Email dalam seminggu&#39;<br>    END AS frekuensi_email<br>FROM summary_transaction;</pre><p>Result :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nF6prtaH_MjzsQMKh_U3fg.png" /></figure><p>For the execution of sending email marketing, we can take an example by issuing a list of customers who will be sent 4–5 emails for shoe products. To do this, I can use the WHERE command and the logical AND operator for this task. Here is the SQL command I will use:</p><pre>SELECT DISTINCT Customer_ID<br>FROM summary_transaction<br>  WHERE Average_transaction &lt; 1000000 and product =  &#39;Sepatu&#39;;</pre><p>By using the command above, I get a list of customers who will be sent email marketing for shoe products.</p><p>Q3. Next, I prepared DQ-Shop’s historical sales data for stock preparation during the <em>year-end </em>sales period. The following table reports the need for team leaders to prepare procurement of goods during the <em>year-end</em> sales period.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qhRwOWtSAdqD6JK64r4ueg.png" /></figure><p>I don’t need logical operators to generate stock analysis reports. I just do a simple query to get the data.</p><p>In the example above, I want to get data on the total items sold for each product, therefore, I can use the ‘GROUP BY Product’ command to get aggregated data on the total sales for each product.</p><p>For the record, I can use the command ‘GROUP BY Product’ or can use ‘GROUP BY 1’ by adjusting the index position in the SQL command (in this case the product variable is the first column, so it can be replaced with ‘GROUP BY 1’).</p><pre>SELECT DISTINCT Product AS Produk,<br>avg(Average_Transaction)AS &#39;Jumlah transaksi (Rupiah)&#39;,<br>sum(Count_Transaction)AS &#39;Barang terjual&#39;<br>FROM summary_transaction<br>GROUP BY Product;</pre><p>Result :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eC07XSwozCnhL61sEhWHuw.png" /></figure><p>Q4. First of all, to be able to complete this project, I can use the raffle table for retail data that has been prepared by the marketing team. This table contains customer data, total unique products purchased, along with the average number of transactions made.</p><p>Here’s a table that I can use for this raffle program :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aRfhgpk8dM0eY9_rGrhhBw.png" /></figure><p>From the data_retail_rafian table, I need to find and display customers who have shopped at 3 (three) different products and the average purchase of these three products / more products is more than IDR 1,500,000.-.</p><pre>SELECT DISTINCT Customer_ID<br>FROM data_retail_undian<br>  WHERE Unik_produk = 3 and Rata_rata_transaksi &gt; 1500000;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/230/1*8TfyKAu51XFF5S-BfechOA.png" /></figure><p>By using this SQL command, <strong>I got about 849 customers who are entitled to take part in the main draw</strong>.</p><p>Furthermore, to find customers who meet the criteria beyond the previous criteria, I can use the ‘NOT’ and ‘AND’ logic functions in the ‘WHERE’ command.</p><pre>SELECT DISTINCT Customer_ID<br>FROM data_retail_undian<br>  WHERE NOT (Unik_produk &gt;= 3 AND Rata_rata_transaksi &gt;= 1500000);</pre><p>By using the right SQL commands, <strong>I got about 72,000 customers who are eligible to enter the second draw.</strong></p><p>Through this project, I have successfully completed Utilization of SQL Logical Operators For Company Marketing Strategy. From the material that I have studied and practiced, I have:</p><ul><li>Be able to understand what the Boolean data type is (TRUE/FALSE)</li><li>Able to understand what a logical operator is and its types (AND, OR, NOT) and be able to show the results of the operation of this operator in the SELECT command</li><li>Able to use logical operators in the WHERE clause to filter data (filtering)</li></ul><p>Hope you found it helpful! Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8178ca47728a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[8 Week SQL Challenge: Case Study #3 Foodie-Fi]]></title>
            <link>https://medium.com/@alfiramdhan/8-week-sql-challenge-case-study-3-foodie-fi-1f4c124049d2?source=rss-82c640d9f481------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f4c124049d2</guid>
            <category><![CDATA[portfolio]]></category>
            <category><![CDATA[8-week-sql-challenge]]></category>
            <category><![CDATA[case-study-solutions]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[Alfiramdhan]]></dc:creator>
            <pubDate>Mon, 09 Jan 2023 11:01:33 GMT</pubDate>
            <atom:updated>2023-01-10T08:50:12.181Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Subscription Style Analysis with SQL</strong></h4><p>Hi everyone,</p><p>I just completed Week 3 of the <a href="https://8weeksqlchallenge.com/case-study-3/">#8weekSQLchallenge by Danny Ma</a>.<br>I really enjoy working with SQL. I am glad that after completing Case Study 1 and 2, I am more confident with SQL window functions and complex queries. I noticed that some of the functionality came to me quite naturally. For example, CASE functions, JOIN functions, UNNEST functions, regular expressions I can use them all the time.</p><p>Today I will share another SQL that I am working on. This challenge is the Third challenge of the <a href="https://8weeksqlchallenge.com/case-study-3/">#8weekSQLchallenge by Danny Ma</a>. You can check out the challenge <a href="https://8weeksqlchallenge.com/case-study-1/">here</a>!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NwXd7BDcln14dBFJKc8UOA.png" /></figure><h4>1. Project Background</h4><p><a href="https://8weeksqlchallenge.com/case-study-3/">Foodie-Fi</a> is a subscription based businesses — streaming service that only had food related content, something like Netflix but with only cooking shows.</p><p>Danny as CEO and founder, realised that there was a large gap in the market. He finds a few smart friends to launch his new start-up 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>In this project, you will extract and analyse performance by focusing on using subscription- style digital data (only 2 tables) to answer subscriber behavior and tell the story of how you have been able to generate that growth.</p><h4>2. Data Preparation</h4><h4>2.1 Create database and schema</h4><p>For this case study, I used PostgreSQL then I create the database, schema and table by using menu options after right clicking on database as shown in following image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I9DdAyQcYWncRYKFn4WEog.png" /><figcaption>Tabel 1. Create Database</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xc_grwP-RJ8eve77w9DFeA.png" /><figcaption>Tabel 2. Create Schema</figcaption></figure><h4><strong>2.3 Entity Relationship Diagram (ERD)</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sIzRVXQafXuKxRoM3xUpfA.png" /></figure><h4>2.3 Create Tables</h4><p>Once the database and schema are created, then the two tables are created according to the following SQL query :</p><h4>a. Plans</h4><p>Records consist of plan id, plan name and price. There are 5 rows in this table. As we can see, 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/1024/1*AucMJM92jWt1GVEHpHK9PA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5OXjOQ6-zlQzQenVTgxXsw.png" /><figcaption>Tabel 3. Plans</figcaption></figure><h4>b. <strong>Subscriptions</strong></h4><p>Records consist of customer id, plan id and the exact date where specific plan id starts. There are 2650 rows in this table.</p><p>Customer subscriptions shows 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. 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/1024/1*U8k4yOKVkpX-jpLNYWbibA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hbRyaNZK2qxKO5Mf1nXONw.png" /><figcaption>Tabel 4. Subscription</figcaption></figure><h4>3. Project Goal</h4><p>This project is split into an initial data understanding question before diving straight into data analysis questions before finishing with 1 single extension challenge.</p><h4><strong>3.1 Customer Journey</strong></h4><p>Based off the sample customers provided in the subscriptions table, write a brief description about each customer’s onboarding journey.</p><h4><strong>3.2 Objectives</strong></h4><p>• How is streaming service business performance?</p><h4><strong>3.3 Problems Question</strong></h4><ol><li>How many customers has Foodie-Fi ever had?</li><li>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?</li><li>What plan start_date values occur after the year 2020 for our dataset? Show the breakdown by count of events for each plan_name?</li><li>What is the customer count and percentage of customers who have churned rounded to 1 decimal place?</li><li>How many customers have churned straight after their initial free trial — what percentage is this rounded to the nearest whole number?</li><li>What is the number and percentage of customer plans after their initial free trial?</li><li>What is the customer count and percentage breakdown of all 5 plan_name values at 2020–12–31?</li><li>How many customers have upgraded to an annual plan in 2020?</li><li>How many days on average does it take for a customer to an annual plan from the day they join Foodie-Fi?</li><li>Can you further breakdown this average value into 30 day periods (i.e. 0–30 days, 31–60 days etc)</li><li>How many customers downgraded from a pro monthly to a basic monthly plan in 2020?</li></ol><h4>4. <strong>Analysis and Visualization</strong></h4><h4><strong>4.1. Customer Journey</strong></h4><p><strong>1. Write a brief description about each customer’s onboarding journey</strong>.</p><pre>SELECT customer_id,<br> plan_name,<br> start_date<br>FROM foodie_fi.subscriptions t1<br>JOIN foodie_fi.plans t2 ON t1.plan_id = t2.plan_id;</pre><p>Result :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A_EWh__V3iUTMrj-G7dNHw.png" /></figure><p>Insight :</p><p>As you can see, the customer number 4 started the trial plan in 2020–01–17 and upgraded the plan to basic monthly a week later, until the customer number 1 churned the plan in 2020–04–21. That’s how you read the customer’s journey.</p><h4><strong>4.2. Data Analysis Questions</strong></h4><p><strong>Q1. How many customers has Foodie-Fi ever had?</strong></p><pre>SELECT COUNT(DISTINCT customer_id)as total_customers<br>FROM foodie_fi.subscriptions;</pre><p>Result :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*I5bj4qTgUaMjir5dZ5i1Qw.png" /></figure><p>Foodie-Fi has 1000 subscribers.</p><p><strong>Q2. 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?</strong></p><pre>SELECT EXTRACT(month from start_date)as months,<br> COUNT(plan_id)as monthly_distribution<br>FROM foodie_fi.subscriptions<br>WHERE plan_id = 0<br>GROUP BY 1<br>ORDER BY 1;</pre><p>Result :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*AkKBn7xgUBiqCqul_Ap4lA.png" /></figure><p>Insight :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*BOKJ8H6izIRKCzxFRowHwA.png" /></figure><p>The distribution of the number of subscribers reached its highest figure in March.</p><p><strong>Q3. What plan start_date values occur after the year 2020 for our dataset? Show the breakdown by count of events for each plan_name?</strong></p><pre>SELECT plan_name,<br> COUNT(t1.plan_id)as count_event<br>FROM foodie_fi.subscriptions t1<br>LEFT JOIN foodie_fi.plans t2<br> ON t1.plan_id = t2.plan_id<br>WHERE EXTRACT(year from start_date) &gt; 2020<br>GROUP BY 1<br>ORDER BY 2 DESC;</pre><p>Result :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jf62dWnRz-kZP0fgcqL5jA.png" /></figure><p>Insight :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*4YsuA9TteBj0AjfaoDv5ig.png" /></figure><p>The number of subscribers who churned the plan was the biggest one after the year 2020, with 71 subscribers.</p><p><strong>Q4. What is the customer count and percentage of customers who have churned rounded to 1 decimal place?</strong></p><p>To find the percentage we can calculate the number of rows multiplied by 100 divided by the total number of customers.</p><pre>SELECT COUNT(*)as num_churn,<br>  CAST(COUNT(*)*100::FLOAT / (SELECT COUNT(DISTINCT customer_id)as total_customer<br>          FROM foodie_fi.subscriptions)::FLOAT AS NUMERIC)as pct_churn<br>FROM foodie_fi.subscriptions<br>WHERE plan_id = 4;</pre><p>Result :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*EAtMBLUpcw8Va95AfuVIxw.png" /></figure><p>Insight :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*WmhMF9oarzEOiSCv8i8EiA.png" /></figure><p>There are 307 customers who have churned, which 30.7% of customers who have churned the plans.</p><p><strong>Q5. How many customers have churned straight after their initial free trial — what percentage is this rounded to the nearest whole number?</strong></p><p>We can use CTE to create a temporary result that can be referred later on. LEAD clause is used to look forward a number of rows and access data of that row from the current row.</p><p>Then we named the result from LEAD clause as lead_plan so we can recall it outside the CTE set. Filter the plan_id = 0 and next_plan = 4 because we want to find the percentage who have churned after trial.</p><pre>WITH lead_plan AS(<br>SELECT *,<br> LEAD(plan_id,1) OVER(PARTITION BY customer_id ORDER BY start_date)as next_plan<br>FROM foodie_fi.subscriptions<br>)<br> SELECT COUNT(*)AS num_churn,<br>  CAST(COUNT(*)*100::FLOAT / (SELECT COUNT(DISTINCT customer_id)as total_customer<br>       FROM foodie_fi.subscriptions)::FLOAT AS NUMERIC)as pct_churn<br> FROM lead_plan<br> WHERE plan_id = 0 and next_plan = 4;</pre><p>Result :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t6gnh9_LzBmKjvUxjf7TlQ.png" /></figure><p>Insight :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*vzOzv3rcsk4elBrKlcXzCQ.png" /></figure><p>There are 92 customers who have churned straight after their initial free trial, which 9% of the customer base.</p><p><strong>Q6. What is the number and percentage of customer plans after their initial free trial?</strong></p><p>To breakdown all plan after their initial free trial, there are few steps to do:</p><p>We can use CTE to create a temporary result that can be referred later on. LEAD clause is used to look forward a number of rows and access data of that row from the current row.</p><p>Then we named the result from LEAD clause as lead_plan so we can recall it outside the CTE set. Filter the plan_id = 0 and next_plan IS NOT NULL because we want to find the percentage after trial plan.</p><pre>WITH lead_plan AS(<br>SELECT *,<br> LEAD(plan_id,1) OVER(PARTITION BY customer_id ORDER BY start_date)as next_plan<br>FROM foodie_fi.subscriptions<br>)<br> SELECT next_plan,<br>  COUNT(*)AS num_churn,<br>  CAST(COUNT(*)*100::FLOAT / (SELECT COUNT(DISTINCT customer_id)as total_customer<br>      FROM foodie_fi.subscriptions)::FLOAT AS NUMERIC)as pct_churn<br> FROM lead_plan<br> WHERE plan_id = 0 and next_plan IS NOT NULL<br> GROUP BY 1<br> ORDER BY 1;</pre><p>Result :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QHk2iClkcrIvaEqdDTeTPg.png" /></figure><p>Insight :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*yOjytJBIC03PXmaQDDwjPA.png" /></figure><ul><li>54.5% of customers choose basic monthly after their initial trial.</li><li>32.5% of customers choose pro monthly after their initial trial.</li><li>3.7% of customers choose pro annual after their initial trial.</li><li>9.2% of customers choose churn after their initial trial.</li></ul><p><strong>Q7. What is the customer count and percentage breakdown of all 5 plan name values at 2020–12–31?</strong></p><p>To <strong>breakdown all 5 plan name at the exact date which is 2020–12–31</strong>, there are few steps to do:</p><ul><li>Create CTE for dates after 2020–12–31 for each customer. then named it as ‘table next date’.</li><li>Create other CTE to count number of customers for each plan,, then filter dates up to 2020–12–31 and subsquent dates of each customer</li><li>Last, outside the CTE we call the plan id, number of customers of each plans, and the percentage of each plans</li></ul><pre>WITH date_plan AS(<br>SELECT *,<br> LEAD(start_date,1) OVER(PARTITION BY customer_id ORDER BY start_date)as next_date<br>FROM foodie_fi.subscriptions<br>),<br><br>num_customer AS(<br> SELECT plan_id,<br>  COUNT(DISTINCT customer_id)AS number_customer<br> FROM date_plan<br> WHERE (next_date IS NOT NULL AND (&#39;2020-12-31&#39;::DATE &gt; start_date AND &#39;2020-12-31&#39;::DATE &lt; next_date))<br>         OR (next_date IS NULL AND &#39;2020-12-31&#39;::DATE &gt; start_date)<br> GROUP BY 1<br>)<br><br> SELECT plan_id,<br>  number_customer,<br>  ROUND(CAST(number_customer *100 / (SELECT COUNT(DISTINCT customer_id)as total_customer<br>       FROM foodie_fi.subscriptions) AS NUMERIC),2)as pct_each_plan<br> FROM num_customer;</pre><p>Result :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*ciGanHCHIXFC6UHGEOnC3w.png" /></figure><p>Insight :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*8N7-6M0H2fol2x5J6N_RFQ.png" /></figure><p>Plan_id 2 or Pro Monthly plan has the highest percentage of subscribers until 31- 12–2020.</p><p><strong>Q8. How many customers have upgraded to an annual plan in 2020?</strong></p><pre>WITH lead_plan AS(<br>SELECT *,<br> LEAD(plan_id,1) OVER(PARTITION BY customer_id ORDER BY start_date)as next_plan<br>FROM foodie_fi.subscriptions<br>)<br> SELECT COUNT(*)AS num_annual<br> FROM lead_plan<br> WHERE next_plan = 3<br>  and EXTRACT(year from start_date) = &#39;2020&#39;;</pre><p>Result :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*r-Tp6NXprx-FlqvPGNFeLw.png" /></figure><p>There are 253 customers who have upgraded to annual in 2020.</p><p><strong>Q9. How many on average does it take for a customer to annual plan from the day they join Foodie-Fi?</strong></p><p>Create two CTEs to distinguish the plan_id, first cte to filter the annual plan and the second CTE is to filter the trial plan using the WHERE clause. Then, calculate the number of days between two date values.</p><p>Next, we find the average of days for how long the customers take the annual plan using AVERAGE clause.</p><pre>WITH join_date AS(<br> SELECT customer_id,<br>  start_date AS trial_date<br> FROM foodie_fi.subscriptions<br> WHERE plan_id = 0<br>),<br><br>annual_date AS(<br> SELECT customer_id,<br>  start_date as pro_annual_date<br> FROM foodie_fi.subscriptions<br> WHERE plan_id = 3<br>)<br> SELECT ROUND(AVG(pro_annual_date - trial_date),2)as avg_days<br> FROM join_date, annual_date<br>  WHERE join_date.customer_id = annual_date.customer_id;</pre><p>Result :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*lW8ddSPY56ccZV0sGhv--g.png" /></figure><p>On average, it takes 105 days for a customer take an annual plan from the day they joined Foodie-Fi.</p><p><strong>Q10. Can you further breakdown this average value into 30 day periods? (i.e. 0–30 days, 31–60 days etc)</strong></p><p>From the previous query we can add a few statements to breakdown this average value into 30 day periods (i.e. 0–30 days, 31–60 days etc).</p><ul><li>Find out min and max values. Then we got Min 7 days and Max 346 for customer to annual plan from the day they join Foodie-Fi</li><li>Create the new CTE named bins and use the WIDTH_BUCKET function to returns the position of a specified operand in some specified buckets (named it as avg_days_to_upgrade in bins CTE).</li><li>The syntax : WIDTH_BUCKET(operand, low, high, count). We can create range start from 0 to 360 with 0 as minimum value, 360 as maximum value and 12 as number of rows</li><li>Use || concatenate operator to create the 30 days period.</li></ul><pre>WITH join_date AS(<br> SELECT customer_id,<br>  start_date AS trial_date<br> FROM foodie_fi.subscriptions<br> WHERE plan_id = 0<br>),<br><br>annual_date AS(<br> SELECT customer_id,<br>  start_date as pro_annual_date<br> FROM foodie_fi.subscriptions<br> WHERE plan_id = 3<br>)<br> SELECT Min(pro_annual_date - trial_date)as min_days,<br>  Max(pro_annual_date - trial_date)as max_days<br> FROM join_date, annual_date<br>  WHERE join_date.customer_id = annual_date.customer_id;</pre><pre>WITH join_date AS(<br> SELECT customer_id,<br>  start_date AS trial_date<br> FROM foodie_fi.subscriptions<br> WHERE plan_id = 0<br>),<br><br>annual_date AS(<br> SELECT customer_id,<br>  start_date as pro_annual_date<br> FROM foodie_fi.subscriptions<br> WHERE plan_id = 3<br>),<br><br>bins AS(<br> SELECT WIDTH_BUCKET(pro_annual_date - trial_date, 0, 360, 12) AS avg_days_to_upgrade<br> FROM join_date t1<br> JOIN annual_date t2<br>         ON t1.customer_id = t2.customer_id<br>)<br><br> SELECT ((avg_days_to_upgrade - 1)*30 || &#39;-&#39; || (avg_days_to_upgrade)*30) AS &quot;30-day-range&quot;,<br>  COUNT(*) as total<br> FROM bins<br> GROUP BY avg_days_to_upgrade<br> ORDER BY avg_days_to_upgrade;</pre><p>Result :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*ANOmKX9zSODTxCRyGgPBRg.png" /></figure><p><strong>Q11. How many customers downgraded from a pro monthly to a basic monthly plan in 2020?</strong></p><pre>WITH lead_plan AS( <br> SELECT *,<br>  LEAD(plan_id, 1) OVER(PARTITION BY customer_id ORDER BY start_date)as next_plan<br> FROM foodie_fi.subscriptions<br>)<br> SELECT COUNT(DISTINCT customer_id)as number_customer<br> FROM lead_plan<br> WHERE plan_id = 2<br>  AND next_plan = 1<br>   AND EXTRACT(year from start_date) = &#39;2020&#39;;</pre><p>Result :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*4J5umroeSpnKlUMhu6j3AQ.png" /></figure><h4><strong>5. Insight and Recommendation</strong></h4><p><strong>5.1 Insight :</strong></p><ul><li>Foodie-Fi has a total of 1000 subscribers, with customer journey from trial plan reaching the highest number of subscribers in March.</li><li>The number of subscribers who churned the plan was the biggest one after the year 2020, with 71 subscribers.</li><li>Of the total 30.7% of subscribers who cancelled plans, around 9.2% of the subscribers base had churned right after their initial free trial.</li><li>The number of subscribers choosing a ‘Basic Monthly’ was the largest after the initial trial, with 54.5%. While the lowest out of all plan was ‘Pro Annual’, with 3.7%.</li><li>Even though ‘Basic Monthly’ was popular overall but till 2020–12–31, the ‘Pro Monthly’ was the most chose one.</li><li>There were 253 subscribers who had upgraded to annual in 2020. On average, it took customers 105 days to pick up their annual package from the time they joined Foodie-Fi.</li><li>There was none of the subscribers downgraded from a pro monthly to a basic monthly plan in 2020.</li></ul><h4><strong>5.2 Recommendation :</strong></h4><ul><li>Find out what makes a ‘Basic Monthly as their favourite plan for subscribers chose first after the initial trial and apply the same strategy in other plans.</li><li>The highest number of churned after 2020, it can be an early diagnosis that the customer is not interested or dissatisfied with the service.</li><li>With more than 190 customers who have upgraded to become an annual in 2020, Danny and the team can focus campaigns and budgets on loyal and potential subscribers.</li><li>The company should utilize customer and product information for marketing strategies that will help in get loyal subscriber.</li></ul><p>You can see the full query on my Github by clicking this <a href="https://github.com/alfiramdhan">link</a>. Let me know if you find an easier way to ask this challenge. Thank you very much for reading and I hope you find this post useful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f4c124049d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[8 Week SQL Challenge: Case Study #1 Danny’s Dinner]]></title>
            <link>https://medium.com/@alfiramdhan/restaurant-database-analysis-with-sql-b1fd390d21e?source=rss-82c640d9f481------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1fd390d21e</guid>
            <category><![CDATA[portofolio]]></category>
            <category><![CDATA[case-study-solutions]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[8-week-sql-challenge]]></category>
            <dc:creator><![CDATA[Alfiramdhan]]></dc:creator>
            <pubDate>Tue, 03 Jan 2023 04:00:41 GMT</pubDate>
            <atom:updated>2023-09-25T03:08:39.567Z</atom:updated>
            <content:encoded><![CDATA[<h4>Restaurant Database Analysis with SQL</h4><p>Hi everyone!!!</p><p>Today I will share about SQL, especially the SQL challenge that I’m working on. This challenge is the first challenge of the 8 Week SQL challenge. As you know, this SQL challenges really improve my logical thinking to solve the problem through the query language. Check out the challenge <a href="https://8weeksqlchallenge.com/case-study-1/">here</a>!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-F9w1V32zhf0UOof6A-iwA.png" /></figure><h3><strong>1. Project Background</strong></h3><p><a href="https://8weeksqlchallenge.com/case-study-1/">Danny’s Diner</a> is in need of your assistance to use their data to help them run the business, a little restaurant which has just open and launched its 3 favourite foods : sushi, curry and ramen.</p><p>Danny as the owner, opens up a cute little restaurant in the beginning of 2021. He has captured some very basic data from few months of operation but have no idea how to use the data to run the business.</p><p>You will extract and analyze performance data from Danny’s Diner to quantify the customer’s overview and tell the story of how you have been able to generate that growth.</p><h3><strong>2. Data Preparation</strong></h3><h4>2.1 <strong>Create database and schema</strong></h4><p>For this case study, I used PostgreSQL then I create the database, schema and table by using menu options after right clicking on database as shown in following image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MyB9hR7bK8wNAk6x0FiWmA.png" /><figcaption>Tabel 1. Create Database</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jiHdzAueaZmRkALRn5-pUA.png" /><figcaption>Tabel 2. Create Schema</figcaption></figure><h4>2.2 Create Tables</h4><p>Once the database and schema are created, then the three tables are created according to the following SQL query :</p><h4><strong>a. Sales</strong></h4><p>Records consist of customer’s orders with customer id, date when the order is ordered, product id of item ordered. There are 15 rows in this table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iwe_Dit6GdBbuueHQaaYtg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mw8n8ashW-CyUajsidLtqg.png" /><figcaption>Tabel 3. Sales</figcaption></figure><h4>b. Menu</h4><p>Records consist of product id, name of the product and price of the product. There are 3 rows in this table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6DagweFy9DIbBz5Vp9BpMA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bI_CPL4pbVxBfgYRx5AuSg.png" /><figcaption>Tabel 4. Menu</figcaption></figure><h4>c. Members</h4><p>Records consist of customer id and date when customer is registered as member. There are 2 rows in this table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gvK4pmX-0zfykpvO7KwqJA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3JsyKudZihsYdBKLDMFb9Q.png" /><figcaption>Tabel 5. Members</figcaption></figure><h3>3. Project Goal</h3><p>Danny needs your help to gain insights to provide a better, more personalized experience for his loyal customers, including</p><ul><li>Customer visit patterns</li><li>Total amount spent and favorite menus</li><li>Expansion of existing customer loyalty programs</li></ul><h4><strong>3.1 Problems Question</strong></h4><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 is 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 customer A and B have at the end of January?</li></ol><h3>4. <strong>Analysis and Visualization</strong></h3><h4><strong>Q1. What is the total amount each customer spent at the restaurant?</strong></h4><pre>select s.customer_id,<br> sum(m.price)as total_spent<br>from dannys_dinner.sales s<br>join dannys_dinner.menu m on s.product_id = m.product_id<br>group by customer_id <br>order by customer_id;</pre><p>Result :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*R8xWmErLASHoDm0VOgnArg.png" /></figure><h4><strong>Q2. How many days has each customer visited the restaurant?</strong></h4><pre>SELECT customer_id,<br>  COUNT(DISTINCT order_date)as number_days<br>FROM dannys_dinner.sales<br>GROUP BY 1<br>ORDER BY 1;</pre><p>Result :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*qegbmnaCE5358ByU1z9lkg.png" /></figure><p>Insight :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IST16VzzLitQdB2dsyYDpw.png" /></figure><p>Even though it is not customer B who spends the most money in total, it is customer B who visits the restaurant the most.</p><p>Meanwhile, Customer A generates the highest total spend and this can be an initial diagnosis of a customer being interested or satisfied with the menu.</p><h4><strong>Q3. What was the first item from the menu purchased by each customer?</strong></h4><p>To get the first item purchased, we can use window function rank () to rank the items ordered by each customer in CTE. Then once we get the rank, we can filter rows using WHERE clause.</p><pre>with index_rank as(<br> select customer_id,<br>  order_date,<br>  product_id,<br>  dense_rank() over(partition by customer_id order by order_date)as rnk<br> from dannys_dinner.sales<br>) <br>select customer_id,<br> order_date,<br> product_name<br>from index_rank id<br>join dannys_dinner.menu mn on id.product_id = mn.product_id<br>where rnk = 1<br>order by 1;  </pre><p>Result :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*NR5ZTY8sXfu1ZCdQJJbX-A.png" /></figure><h4><strong>Q4. What is the most purchased item on the menu and how many times was it purchased by all customers?</strong></h4><pre>SELECT t1.product_id,<br>         product_name,<br>         COUNT(t1.product_id)as total_items<br>FROM dannys_dinner.sales t1<br>LEFT JOIN dannys_dinner.menu t2 ON t1.product_id = t2.product_id<br>GROUP BY 1,2<br>ORDER BY 3 DESC;</pre><p>Result :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*Pr8XsmgrqIx36HB1xMq8bg.png" /></figure><p>Insight :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QXtPcm4D_RFW8m5N_L_hAA.png" /></figure><p>Even though 66.7% of customers chose curry as the first menu they ordered. It turns out that the most purchased menu is ramen, purchased 8 times for a total of 53.3%</p><h4><strong>Q5. Which item was the most popular for each customer?</strong></h4><pre>WITH rank_order AS (<br> SELECT t1.customer_id,<br>  product_name,<br>  COUNT(t1.product_id)as total_items,<br>  DENSE_RANK () OVER(PARTITION BY t1.customer_id ORDER BY COUNT(t1.product_id) desc )as rn<br> FROM dannys_dinner.sales t1<br> JOIN dannys_dinner.menu t2 ON t1.product_id = t2.product_id<br> GROUP BY 1,2<br> ORDER BY 3 DESC<br>)<br> <br>SELECT customer_id,<br> product_name,<br> total_items,<br> rn<br>FROM rank_order<br>WHERE rn=1<br>ORDER BY 1;</pre><p>Result :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RENzetX3Dr3iaQGS3XVl3g.png" /></figure><p>Insight :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*05wLzuYai83sMjj7bFn40g.png" /></figure><ul><li>The most popular item for customer A and C was ramen, they purchased it 3 times</li><li>Meanwhile, Customer B enjoys all items on the menu.</li><li>75% of customers choose the ramen menu as their favorite menu.</li></ul><h4><strong>Q6. Which item was purchased first by the customer after they became a member?</strong></h4><p>Let’s consider that if the order_date matches the membership date then the purchase made on this date, was the first customer’s purchase as a member. It means we need to include this date in the WHERE clause.</p><pre>with ranking AS(<br> SELECT mm.customer_id,<br>  order_date,<br>  product_name,<br>  DENSE_RANK() OVER(PARTITION BY mm.customer_id ORDER BY order_date)as rnk<br> FROM dannys_dinner.members mm<br> JOIN dannys_dinner.sales s on mm.customer_id = s.customer_id<br> JOIN dannys_dinner.menu mn on s.product_id = mn.product_id<br> WHERE order_date &gt;= join_date<br>)<br> SELECT customer_id,<br>  order_date,<br>  product_name<br> FROM ranking<br> WHERE rnk = 1;</pre><p>Result :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fr3_x84HSjrlTxfrAiL2hg.png" /></figure><h4><strong>Q7. Which item was purchased just before the customer became a member?</strong></h4><pre>SELECT mm.customer_id,<br> order_date,<br> product_name,<br> DENSE_RANK() OVER(PARTITION BY mm.customer_id ORDER BY order_date DESC)as rnk<br>FROM dannys_dinner.members mm<br>JOIN dannys_dinner.sales s on mm.customer_id = s.customer_id<br>JOIN dannys_dinner.menu mn on s.product_id = mn.product_id<br>WHERE order_date &lt; join_date;</pre><p>Result :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LnTvB3DCArmS6pfa6j0kbQ.png" /></figure><p>Insight :</p><ul><li>Customer A’s last order before becoming a member was sushi and curry</li><li>Meanwhile, Customer B’s last order before becoming a member was sushi</li></ul><h4><strong>Q8. What is the total items and amount spent for each member before they became a member?</strong></h4><pre>WITH total AS( <br> SELECT mm.customer_id,<br>  order_date,<br>  COUNT(mn.product_id)as total_items,<br>  SUM(price)as total_amount<br> FROM dannys_dinner.members mm<br> JOIN dannys_dinner.sales s on mm.customer_id = s.customer_id<br> JOIN dannys_dinner.menu mn on s.product_id = mn.product_id<br> WHERE order_date &lt; join_date<br> GROUP BY 1,2<br> ORDER BY 1,2<br>)<br> SELECT customer_id,<br>  SUM(total_items)as total_items,<br>  SUM(total_amount)as total_amount<br> FROM total<br> GROUP BY 1;</pre><p>Result :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xsHTkDOSKbpH_jcK13B0hA.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><h4><strong>Q9. If each $1 spent equates to 10 points and sushi has a 2x points multiplier — how many points would each customer have?</strong></h4><p>Since points value only for members so we need to specify for each customer after became a member.</p><pre>WITH total AS(<br> SELECT *,<br>  CASE WHEN product_id = 1 THEN price * 20<br>   else price * 10<br>  END as point<br> FROM dannys_dinner.menu<br>) <br> SELECT s.customer_id,<br>  SUM(point)as total_point<br> FROM total t<br> JOIN dannys_dinner.sales s on t.product_id = s.product_id<br> GROUP BY 1<br> ORDER BY 1;</pre><p>Result :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*awtALHun0BSW3pmLBw72xg.png" /></figure><ul><li>Total points for Customer A is 860</li><li>Total points for Customer B is 940</li><li>Total points for Customer C is 360</li></ul><h4><strong>Q10. 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 customer A and B have at the end of January?</strong></h4><ul><li>First Step : calculate the total points for each customer as in Question 9</li><li>Once we get total point, we can get total points for each customer at the end of January</li><li>Since the hint is end of January so we can use CASE WHEN function and Interval function to retrieve data.</li></ul><pre>WITH dates_cte AS <br>(<br>   SELECT *, <br>      date(join_date + integer &#39;6&#39;) first_week, <br>      date(&#39;2021-01-31&#39;) end_month<br>   FROM dannys_dinner.members mm<br>),<br>point AS(<br>SELECT d.customer_id, s.order_date, d.join_date, d.first_week, d.end_month, m.product_name, m.price,<br>   SUM(CASE<br>      WHEN m.product_name = &#39;sushi&#39; THEN 2 * 10 * m.price<br>      WHEN s.order_date BETWEEN d.join_date AND d.first_week THEN 2 * 10 * m.price<br>      ELSE 10 * m.price<br>      END) points<br>FROM dates_cte d<br>JOIN dannys_dinner.sales s ON d.customer_id = s.customer_id<br>JOIN dannys_dinner.menu m ON s.product_id = m.product_id<br>WHERE s.order_date &lt; d.end_month<br>GROUP BY 1,2,3,4,5,6,7<br>)<br> SELECT customer_id,<br>  SUM(points)as total_point<br> FROM point  <br> GROUP BY 1; </pre><p>Result :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*yf1BGFNe92Eye9V2yX2zMg.png" /></figure><ul><li>Total points for Customer A is 1,370</li><li>Total points for Customer B is 820</li></ul><h3><strong>5. Insight and Recommendation</strong></h3><h4><strong>5.1 Insight :</strong></h4><ul><li>Customer patterns improved during January. For customer A’s total spend, that increased 67% from $25 to $76. And for customer B’s total spend, this increased 46% from $40 to $74.</li><li>Customer B was the person who frequents the restaurant the most. Meanwhile, Customer A generated the highest total spending and it could be an initial diagnosis of a customer being interested or satisfied with the menu.</li><li>Ramen was favourite menu for customer A and C whereas B likes all three items equally as per the data.</li><li>Even though Ramen was popular but before and after joining ‘Customer loyalty’ program, both customer ordered ‘sushi’ and ‘curry’.</li><li>Customer A was the first ‘Loyal Customer’ followed by B .</li><li>Customer C has purchased the lowest out of all three customer and also, he is not a member of ‘loyalty program’.</li></ul><h4><strong>5.2 Recommendation :</strong></h4><ul><li>Find out what makes ramen a favorite menu item for customers who make their first order and apply the same strategy in other customers’ cities.</li><li>With the majority of revenue coming from members, Danny and team can focus campaigns and budgets on loyal and potential customers.</li><li>The restaurant should utilize customer and product information for marketing strategies that will help in get loyal customer.</li></ul><p>You can see the full query on my Github by clicking this <a href="https://github.com/alfiramdhan/8Weeks_SQL_Challenge/blob/main/Case%20Study%201%20-%20Danny&#39;s%20Dinner/Readme.md">link</a>. Let me know if you find an easier way to ask this challenge. Thank you very much for reading and I hope you find this post useful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1fd390d21e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Project Data Analysis : Quarterly Reports for B2B Retail]]></title>
            <link>https://medium.com/@alfiramdhan/project-data-analysis-quarterly-reports-for-b2b-retail-abfb2a6e97e7?source=rss-82c640d9f481------2</link>
            <guid isPermaLink="false">https://medium.com/p/abfb2a6e97e7</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[customer-analysis]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Alfiramdhan]]></dc:creator>
            <pubDate>Fri, 04 Nov 2022 13:56:05 GMT</pubDate>
            <atom:updated>2022-11-04T13:56:05.719Z</atom:updated>
            <content:encoded><![CDATA[<h3>Project Data Analysis : Quarterly Reports for B2B Retail</h3><p>Measuring B2B Retail Performance with SQL</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/276/1*BWm6h6Mooq5x8QRIOCD0fQ.jpeg" /></figure><p>This project is provided by <a href="https://academy.dqlab.id/">DQLab</a>, and I will be <strong>reviewing xyz.com’s performance in the 2nd quarter</strong>. xyz.com is a B2B startup that sells various products not directly to end users but to other businesses/companies. As a data-driven company, every decision making is always based on data. And every quarter, the company will hold a townhall to review the company’s performance during the last quarter.</p><p>As I began this project I took into consideration the cycle of a data analysis project : <strong>Business Issue Understanding</strong> (setting research objectives and questions),<strong> Data Understanding</strong>, and <strong>Providing Data Analysis</strong> (Analysis and Insights).</p><h3>Research Question</h3><p>Let’s say the manager wants to know the condition of the company last month (Assume the current year is 2004).</p><p>So based on the information that has been provided, I would like to review:</p><ol><li>How is the current sales growth?</li><li>Is the number of xyz.com customers growing?</li><li>And how many of these customers have made transactions?</li><li>How many customers are still actively transacting?</li><li>What product categories are most purchased by customers?</li></ol><h3>Data Understanding</h3><p>The dataset that I use comes from the following 3 tables :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rI67VeaqChlrrOXgB7DT3Q.png" /><figcaption>Figure 1. Table used in project</figcaption></figure><ol><li>Table <strong>orders_1</strong> : Contains data related to sales transactions for the 1st quarter period (Jan — Mar 2004)</li></ol><pre>-- retrieve data from table</pre><pre>SELECT * FROM orders_1 LIMIT 5;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GsS461cauIo181Ujj_3xUA.png" /><figcaption>Figure 2. Table orders_1</figcaption></figure><p>2. Table o<strong>rders_2</strong> : Contains data related to sales transactions for the 2nd quarter period (Apr — Jun 2004)</p><pre>-- retrieve data from table</pre><pre>SELECT * FROM orders_2 LIMIT 5;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5-nZEVGMNlizTwgFCYGRjA.png" /><figcaption>Figure 3. Table orders_2</figcaption></figure><p>3. <strong>Customer</strong> table: Contains data on customer profiles who register as xyz.com customers</p><pre>-- retrieve data from table</pre><pre>SELECT * FROM customers LIMIT 5;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QKeWVGWFfeRlOh35R1Ic4Q.png" /><figcaption>Figure 4. Table customers</figcaption></figure><p><strong><em>Now, Let’s get started!</em></strong></p><h4>How is the current sales growth?</h4><p>To find out <strong>sales growth</strong>, it can be done by calculating the percentage of last month’s sales with the <strong>previous sales amount</strong> and <strong>the difference between last month’s revenue</strong> and the <strong>previous period’s revenue</strong> :</p><pre><strong>-- Total Sales and Revenue</strong> <strong>in Quarter-1 (Jan, Feb, March)</strong></pre><pre>SELECT SUM(quantity * priceeach)as revenue, COUNT(quantity)as total_sales<br>FROM orders_1<br>WHERE status = &#39;Shipped&#39;;</pre><p>Output :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*dRvLdaCt1_tk-kJ9_zPJ9A.png" /><figcaption>Figure 5. Total Sales and Revenue in Q-1</figcaption></figure><pre><strong>-- Total Sales and Revenue</strong> <strong>in Quarter-2 (Apr, May, June)</strong></pre><pre>SELECT SUM(quantity * priceeach)as revenue, COUNT(quantity)as total_sales<br>FROM orders_2<br>WHERE status = &#39;Shipped&#39;;</pre><p>Output :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*eE6t_ksCf7cND-xtT1F5Rw.png" /><figcaption>Figure 6. Total Sales and Revenue in Q-2</figcaption></figure><p>As the two tables order_1 and order_2 are still separate, the two tables need to be combined to calculate the percentage of overall sales.</p><pre>-- We can use UNION function to combine both tables<br>-- add a new column with the name &quot;quarter&quot; and fill it with the value &quot;1&quot; for table orders_1 and &quot;2&quot; for table orders_2</pre><pre>With table_a AS(<br>     SELECT ordernumber, status, quantity, priceeach, 1 as quarter FROM orders_1<br>      UNION<br>      SELECT ordernumber, status, quantity, priceeach, 1 as quarter FROM orders_2<br>)</pre><pre>SELECT quarter, COUNT(quantity)as total_sales, SUM(quantity * priceeach)as revenue<br>FROM table_a<br>WHERE status = &#39;Shipped&#39;<br>GROUP BY 1;      </pre><p>Output :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*Ihjt15F_kh_dAFKaksq-7Q.png" /><figcaption>Figure 7. Total Sales and Revenue in Q-1 &amp; Q-2</figcaption></figure><p>Furthermore, sales growth calculations with SQL can be performed using the “<em>window function</em>”. But for this project, the calculation of sales growth will be done manually using the following formula:</p><pre><strong>% Growth Sales</strong> = sum (present sales) — sum (past sales)) / sum (past sales) * 100%<br><strong>% Growth Revenue</strong> = sum (present revenue) — sum (past revenue)) / sum (past revenue) * 100%</pre><p><strong>%Growth Sales</strong> = (6717–8694)/8694 = -22%</p><p><strong>%Growth Revenue </strong>= (607548320–799579310)/ 799579310 = -24%</p><p>Based on the above calculation, we know that <strong>Sales Growth</strong> has decreased by <strong>-22.74%</strong> and <strong>Revenue Growth</strong> has decreased by <strong>-24.02%</strong>.</p><h4>Is the number of xyz.com customers growing?</h4><p>The increase in the number of customers can be measured <strong>by comparing the number of customers who registered</strong> in the current period with the <strong>number of customers who registered at the end</strong> of the previous period.</p><pre>With table_b AS(<br>    SELECT customerID, createDate, QUARTER(createDate)as quarter<br>    FROM customers)</pre><pre>SELECT quarter, COUNT(DISTINCT customerID)as total_customers<br>FROM table_b<br>GROUP BY 1;</pre><p>Output :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*336HE1Y0NwKwNxOhiGPxUw.png" /><figcaption>Figure 8. Total Customers who registered</figcaption></figure><h4>How many of these customers have made transactions?</h4><p>Based on the number of customers who registered in the 1st and 2nd quarters, how many have made transactions?</p><pre>SELECT quarter, COUNT(DISTINCT customerID)as total_customers<br>FROM table_b<br>WHERE customerID IN (<br>         SELECT DISTINCT customerID FROM orders_1<br>         UNION<br>         SELECT DISTINCT customerID FROM orders_2<br>)<br>GROUP BY 1;</pre><p>Output :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*71IcACQJ9q5GtjJoFx6mFg.png" /><figcaption>Figure 9. Total Customer who did transaction</figcaption></figure><p>Next we can calculate the percentage of customers did transactions :</p><pre><strong>% Customer Did Transactions </strong>= Sum(total customer who did transaction by quarter) / sum(total customer by quarter) * 100 (%)</pre><p><strong>% Customer Did Transactions</strong>= (25 + 19) * 100 / (43 + 35) = <strong>56.41%</strong></p><p><strong>Based on the calculation above</strong>, we get information that of the total registered customers in the 1st and 2nd quarters, <strong>44 </strong>customers or <strong>56.41% have made transactions.</strong></p><h4>How many customers are still actively transacting?</h4><p><strong>Knowing</strong> how many<strong> customers remain active shows</strong> whether xyz.com is <strong>still popular </strong>with customers for ordering their business needs. It can also form the basis for product and business teams for future product and business development. The metric used is called <strong>retention</strong> group. But for this project, I will calculate retention with a simple SQL query :</p><pre><strong>%Customer Retention Rate</strong> = ((Number of present customers (Q2)) /<br>              Number of customers in the past period (Q1)) x 100 (%)</pre><p>Since we <strong>only have data for 2 periods</strong>, namely 1st and 2nd quarters, the retention that can be calculated is the <strong>retention of customers who shopped in first quarter and returned to shop in second quarter</strong>, while for customers who shopped in Quarter 2, retention can only be calculated in Quarter 3.</p><pre>#Number of customers in the past period (Q1)<br>SELECT COUNT(DISTINCT customerID) as total_customers FROM orders_1;<br>#output = 25</pre><pre>#Number of customers in the present period (Q2)<br>SELECT COUNT(DISTINCT customerID) as total_customers<br>FROM orders_1<br>WHERE customerID IN(SELECT DISTINCT customerID FROM orders_2);<br>#output = 6</pre><pre>#calculate how many customer who remain active in transactions after the first transaction<br>SELECT &#39;1&#39; US quarter,<br>       (COUNT(DISTINCT customerID)*100)/25 as q2<br>FROM orders_1<br>WHERE customerID IN (<br>      SELECT DISTINCT customerID<br>    FROM orders_2<br>);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*lfOdNxnVb80HgGQW-8RAzA.png" /><figcaption>Figure 10. Customer Retention Rate</figcaption></figure><p><strong>% Customer Retention Rate </strong>= (6 / 25) x 100 = 24%</p><p>Based on the data, of the<strong> 25 customers</strong> who made transactions in the<strong> first quarter</strong>, 6 customers or <strong>24%</strong> remained active in the <strong>second quarter</strong>.</p><h4>What product categories are most purchased by customers in Q2?</h4><p>To find out which product categories are purchased the most, it can be done by calculating the total orders and the number of sales from each product category.</p><pre>-- Add a new column by extracting the first 3 characters from the productCode which is the ID for the product category<br>and name it categoryID</pre><pre>with table_d AS(</pre><pre>   with table_c AS(<br>        SELECT substring(productCode,1,3)as categoryID, quantity, orderNumber<br>        FROM orders_2<br>        WHERE status = &#39;Shipped&#39;</pre><pre>   )<br>      SELECT categoryID, COUNT(DISTINCT orderNumber)as total_order, SUM(quantity)as total_sales<br>      FROM table_c<br>      GROUP BY 1)</pre><pre>SELECT * <br>FROM table_d<br>ORDER BY total_order DESC;</pre><p>Output :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*ArQx_vgDT35tMq3ZwAJhmQ.png" /><figcaption>Figure 11. Most Purchased Category</figcaption></figure><h3>Analysis and Insights</h3><p>Based on the data available through SQL queries, we can draw the conclusion that :</p><ol><li>In the second quarter there was a <strong>significant decline</strong> in sales and revenue performance, which decreased by <strong>20% and 24%</strong>;</li><li>The <strong>growth of new customers </strong>also did not show good growth and showed a <strong>downward trend</strong> compared to the previous quarter;</li><li><strong>The interest of new customers</strong> to shop at xyz.com is still <strong>lacking</strong>, only about <strong>56% have made transactions</strong>. It is recommended that the Product team <strong>need to study customer behavior and make product improvements,</strong> so that the conversion rate (register to transaction) can increase;</li><li>The <strong>customer retention rate</strong> is also <strong>very low</strong> at only<strong> 24%</strong>, meaning that many customers who have transacted in the 1st quarter do not return to order in the 2nd quarter (<strong>there are no repeat orders</strong>);</li><li><strong>S18 and S24</strong> category products <strong>contribute about 50%</strong> of total orders and <strong>60% of total sales</strong>, so xyz.com should focus on developing S18 and S24 categories;</li><li><strong>xyz.com experienced negative growth in the 2nd quarter</strong> and needs to make a lot of improvements both in terms of products and marketing business, if you want to achieve the target and have positive growth in the 3rd quarter. The <strong>low retention rate and conversion rate can be an early diagnosis</strong> that customers are not interested/unsatisfied/disappointed in shopping at xyz.com.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=abfb2a6e97e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple Way to Analyze Your Customers Using RFM Analysis]]></title>
            <link>https://medium.com/@alfiramdhan/simple-way-to-analyze-your-customers-using-rfm-analysis-9b819be64a1e?source=rss-82c640d9f481------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b819be64a1e</guid>
            <category><![CDATA[rfm-analysis]]></category>
            <category><![CDATA[postgressql]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Alfiramdhan]]></dc:creator>
            <pubDate>Tue, 25 Oct 2022 13:07:09 GMT</pubDate>
            <atom:updated>2022-10-25T13:51:09.786Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the simplest ways to analyze your customer base is to build an RFM model</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/1*prM1oxg8gUQt72cEyiB3Dg.jpeg" /></figure><h3>What is RFM Analysis?</h3><p>When you run a business selling products or services, every customer is a good customer, right?</p><p>Well, Not exactly.</p><p>Through RFM analysis, you can discover who your real best customers are and make them more than assets. So, Recency-Frequency-Monetary (RFM) analysis is a way of segmenting customers using 3 main metrics: <strong>recency</strong> (how long they last bought), <strong>frequency</strong> (how often they buy), and <strong>monetary</strong> value (how much they spend).</p><p>This analysis can make a huge impact on your business. Whether you want to increase marketing, build loyalty, or reduce churn, RFM analysis is a step in the right direction.</p><p>Continuing the previous <a href="https://medium.com/@alfiramdhan/project-data-analysis-superstore-business-performance-66d0b2844fad">superstore business analysis</a>, in this project, I want to segment customers using RFM analysis to help the marketing strategy team retain top customers and make campaigns more effective. I will perform analysis using PostgreSQL and create visualizations using Google Data Studio.</p><p>I’m using the same <a href="https://github.com/alfiramdhan/Simple-Way-to-Analyze-Your-Customers-Using-RFM-Analysis.git">dataset </a>as the previous project, namely superstore dataset (dummy data) that I got from the bootcamp platform: <a href="https://myskill.id/">MySkill</a>. The dataset represents the number of transactions in Superstores in the US (dummy-dataset) during 2015 to 2018, including its features that allow viewing orders from multiple dimensions: from sales, discount value, order_date, delivery date, product details, and customer information.</p><p><strong><em>Now, Let’s get started!</em></strong></p><p>As it focuses on just three metrics, all you really need is three data points:</p><ul><li><strong>Recency</strong> — last order date</li><li><strong>Frequency</strong> — count of total orders</li><li><strong>Monetary value</strong> — total sales</li></ul><p>These metrics reveal who your repeat purchasers are, which customers are the most loyal over time, and which customers spend the most in your shop.</p><p>To perform RFM analysis, I divided customers into four equal groups according to distribution of values for recency, frequency and monetary values.</p><h3>Create RFM Value</h3><pre>-- Find last_order (R), count_order (F) and avg_amount (M) value<br>-- Create RFM Value :</pre><pre>SELECT customer_id,<br>        MAX(order_date) as last_order,<br>        COUNT(*) as total_order,<br>        AVG(sales) as total_sales<br>FROM store_data<br>WHERE sales IS NOT Null<br>GROUP BY 1;</pre><p>The query above provides the values you’ll need to carry out an RFM analysis. The resulting data will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PfJXWVzglKlBTmJ3YZ_YVQ.png" /><figcaption>Figure 1. RFM Value Table</figcaption></figure><h3><strong>Create RFM Quantiles</strong></h3><p>Once you have a table with data on each of your customers’ recency, frequency, and monetary value, it’s time to start segmenting.</p><p>Then lets divides all users into quantiles using the NTILE function. To create the quantiles, I will use an ntile window function that requires just a few lines of additional SQL at the top of your raw RFM Values Query.</p><pre>-- Create RFM Quantiles :</pre><pre>with RFM_Value as(<br>   SELECT customer_id,<br>     MAX(order_date) as last_order,<br>     COUNT(*) as total_order,<br>     AVG(sales) as total_sales<br>   FROM store_data<br>   WHERE sales IS NOT Null<br>   GROUP BY 1<br>)</pre><pre>  SELECT customer_id,<br>    total_order, #you can show or not#<br>    total_sales, #you can show or not#<br>    ntile(4) OVER (ORDER BY last_order ASC) as rfm_recency,<br>    ntile(4) OVER (ORDER BY total_order DESC) as rfm_frequency,<br>    ntile(4) OVER (ORDER BY total_sales DESC) as rfm_monetary<br>  FROM RFM_Value<br>  ORDER BY rfm_recency DESC;</pre><p>This query returns a table with customer alongside the quantile that each customer falls into for recency, frequency, and monetary value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EY6IovdZWhwqnWg6zoyPiw.png" /><figcaption>Figure 2. RFM Quintiles Table</figcaption></figure><p>The resulting table will give a score between 1 and 4 for each quantile (recency, frequency and monetary value). Looking at recency, a 4 means the customer’s purchase was within the top 25% most recent, while a 1 means the customer is in the bottom 25%.</p><p>In the table above, we can see that while customer with id CC/12430 is in the top 25% of customers for recency, he’s in the bottom 25% for purchase frequency. Meanwhile, VP/21730 hasn’t purchased as recently, but he’s bought multiple small orders.</p><h3>Create RFM Cell</h3><p>By taking the values for each customer, combining them to produce a score from 1 (lowest) to 4 (highest) and then combining the three scores together, you get an easy way to divide customers into segments (or “RFM cells” ; for example : new buyers with high spend (414, 4 for recency, 1 for frequency and 4 for monetary value), near lost but previously loyal customers (143, 1 for recency, 4 for frequency and 3 for monetary value) and so on.</p><pre>-- Create RFM Cell</pre><pre>with RFM_Quantiles as(<br>  with RFM_Value as(<br>      SELECT customer_id,<br>              MAX(order_date) as last_order,<br>              COUNT(*) as total_order,<br>              AVG(sales) as total_sales<br>      FROM store_data<br>      WHERE sales IS NOT Null<br>      GROUP BY 1<br>  ) </pre><pre>  SELECT customer_id,<br>         total_order,<br>         total_sales,<br>         ntile(4) OVER (ORDER BY last_order ASC) as rfm_recency,<br>         ntile(4) OVER (ORDER BY total_order DESC) as rfm_frequency,<br>         ntile(4) OVER (ORDER BY total_sales DESC) as rfm_monetary<br>  FROM RFM_Value<br>  ORDER BY rfm_recency DESC<br>)</pre><pre>SELECT customer_id,<br>  rfm_recency,<br>  rfm_frequency,<br>  rfm_monetary,<br>  rfm_recency*100 + rfm_frequency*10 + rfm_monetary as rfm_cell<br>  FROM RFM_Quantiles;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YKuJmXZa6p-ZogOlc5IgYg.png" /><figcaption>Figure 3. RFM Cell Table</figcaption></figure><p>Now that you have clear RFM cells, you need to create meaningful groupings that can help turn the data into actionable insights.</p><p>The key when segmenting customers is to make the basket large enough to be actionable — Marketers will lose their heads if they feel the need to create 125 separate customer campaigns — but small enough that you can handle them as a group. For example, I will classify the class into 7 (<em>Loyal Customer, Active Customer, Promising New Customer, New Customer, Potential Churners, Need Attention and Lost</em>) potential segments, but if you’re interested in getting more specific, check out this resource for a more powerful version.</p><p>Here’s an example of how you might segment RFM cell data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jvIw_VlyMK5IAD7MKDIJEw.png" /><figcaption>Figure 4. RFM Cell Data Example</figcaption></figure><p>You can create a SQL query that puts customers into the right bucket. To do that, just use <a href="https://blog.panoply.io/postgres-case-statement-basics-by-example">CASE</a>statements to return the segment name based on the RFM cell value:</p><pre>-- Create RFM Cell Value</pre><pre>with RFM_Quantiles as(<br>  with RFM_Value as(<br>      SELECT customer_id,<br>              MAX(order_date) as last_order,<br>              COUNT(*) as total_order,<br>              AVG(sales) as total_sales<br>      FROM store_data<br>      WHERE sales IS NOT Null<br>      GROUP BY 1<br>  )</pre><pre>   SELECT customer_id,<br>         total_order,<br>         total_sales,<br>         ntile(4) OVER (ORDER BY last_order ASC) as rfm_recency,<br>         ntile(4) OVER (ORDER BY total_order DESC) as rfm_frequency,<br>         ntile(4) OVER (ORDER BY total_sales DESC) as rfm_monetary<br>   FROM RFM_Value<br>   ORDER BY rfm_recency DESC<br>)</pre><pre>SELECT customer_id,<br>      total_order,<br>      total_sales,<br>      rfm_recency,<br>      rfm_frequency,<br>      rfm_monetary,<br>      rfm_recency*100 + rfm_frequency*10 + rfm_monetary as rfm_cell,<br>CASE WHEN (rfm_recency &gt;= 3) AND (rfm_frequency  &gt;= 3 ) AND (rfm_monetary &gt;= 3)  THEN &#39;Loyal Customer&#39;<br>     WHEN (rfm_recency &gt;= 3) AND (rfm_frequency  &gt;= 3 ) AND (rfm_monetary between 1 and 3)  THEN &#39;Active Customer&#39;<br>     WHEN (rfm_recency &gt;= 3) AND (rfm_frequency between 1 and 2 ) AND (rfm_monetary &gt;=3 )  THEN &#39;Promising New Customer&#39;<br>    WHEN (rfm_recency &gt;= 3) AND (rfm_frequency between 1 and 2 ) AND (rfm_monetary between 1 and 2)  THEN &#39;New Customer&#39;<br>    WHEN (rfm_recency between 2 and 3) AND (rfm_frequency between 1 and 3 ) AND (rfm_monetary &gt;=3 ) THEN &#39;Potential Churners&#39;<br>   WHEN (rfm_recency between 2 and 3) AND (rfm_frequency between 1 and 4 ) AND (rfm_monetary between 1 and 4 )  THEN &#39;Need Attention&#39;<br>   WHEN (rfm_recency between 1 and 2) AND (rfm_frequency between 1 and 4) AND (rfm_monetary between 1 and 4 ) THEN &#39;Lost&#39;<br>ELSE &#39;other&#39; END as rfm_segment<br>FROM RFM_Quantiles<br>ORDER BY rfm_segment DESC;</pre><p>And the end result is like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WrsBY04jGSqP_J_EXexbJw.png" /><figcaption>Figure 5. RFM Cell Value</figcaption></figure><p>(Here’s the code in <a href="https://github.com/alfiramdhan/Simple-Way-to-Analyze-Your-Customers-Using-RFM-Analysis.git">Github</a>)</p><h3>Data Visualization</h3><p>Now we get the customer segmentation table for analysis then I can load the data into <a href="https://datastudio.google.com/reporting/ae99286d-25f3-4650-815e-c04187991f12">Google Data Studio</a> for data visualization.</p><p>One way to visualize your customers RFM segments is to use a Treemap or grid like the one below, with each segment labeled and size proportionally to the volume of each customer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*GR3v2zezzK81b8YT8m2kkQ.png" /><figcaption>Figure 6. RFM Segment Treemap</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*jaP6wlnVuinH3xX5NjZaMQ.png" /><figcaption>Figure 7. RFM Segment Breakdown</figcaption></figure><p><strong>Here we get some numbers namely</strong>,</p><ul><li>There are <strong>199 Lost Segment Customers </strong>who visited and bought less so far which turned out to be the <strong>biggest sales contribution.</strong> So we can offer <strong>renewals and helpful products</strong> to encourage another purchase. Also we can send them <strong>personalized reactivation campaigns </strong>to reconnect.</li><li>There are each <strong>127 New Customer and 124 Need Attention</strong> who <strong>buy often and recently but low to mid price points</strong>. This group is the second largest <strong>contributing customer in total sales</strong> and can be a concern to increase the number of new subscribers.</li><li>There are <strong>80 Active Customers</strong> who <strong>buy often &amp; recently</strong>, but at <strong>low price points </strong>and<strong> 74 Potential Churners </strong>who high spending but haven’t purchased often or lately. We need send them more campaigns, give them bundling promotions and gift, etc to keep customer active.</li><li>There are each <strong>106 Promising New customers</strong> with large orders and <strong>83 Loyal Customers</strong> who are the best customers among other customers. So we can <strong>give special campaign to retain them.</strong></li></ul><p>That’s the simplicity of RFM Analysis using SQL!! You can make further analysis as many questions as you want.</p><p>You can move from simplistic cells and toward more sophisticated RFM clustering using a K-means model. With clustering, you’d input values for recency, frequency, and monetary value and the algorithm would identify the optimum number of segments as well as which customers fall in each grouping.</p><p>Hope you all have a fruitful Data Analysis journey ! Have a nice day~</p><p><strong>References :</strong></p><p><a href="https://www.optimove.com/resources/learning-center/rfm-segmentation">RFM Segmentation, Analysis &amp; Model Marketing | Optimove</a></p><p><a href="https://clevertap.com/blog/rfm-analysis/">RFM Analysis for Customer Segmentation | CleverTapSmart marketers understand the importance of “know thy customer.” Instead of simply focusing on generating more clicks…clevertap.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b819be64a1e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Basic Python : Work with Pandas, NumPy and Matplotlib]]></title>
            <link>https://medium.com/@alfiramdhan/basic-python-work-with-pandas-numpy-and-matplotlib-74e7054cf915?source=rss-82c640d9f481------2</link>
            <guid isPermaLink="false">https://medium.com/p/74e7054cf915</guid>
            <category><![CDATA[matplotlib]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Alfiramdhan]]></dc:creator>
            <pubDate>Mon, 25 Jul 2022 07:54:38 GMT</pubDate>
            <atom:updated>2022-10-27T03:30:34.653Z</atom:updated>
            <content:encoded><![CDATA[<h3>Basic Python : Work with Pandas, NumPy and Matplotlib</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/1*XciCJTtR0A3rG3H2UQmyuQ.jpeg" /><figcaption>shutterstock.com</figcaption></figure><p>Python is a popular programming language. It can be used to handle big data, perform complex mathematics and also read and modify files. Python has been built with extraordinary Python libraries for data analysis that are used every day in solving problems. In this session, we will use Pandas, NumPy and Matplotlib libraries to answer questions and make visualizations.</p><p>The dataset we are using here is sales data in e-commerce. I call this <em>ecommerce_event</em>, which contains data about product information and a record of events performed by users along with date info. Then, <em>user_profile</em>, which contains a record of user information.</p><p><em>Note: All the queries are written in </em><a href="https://colab.research.google.com/drive/1W-B7Wxo4zqh1_hmoLdJ__S8NnpxSCtEM?usp=sharing"><em>https://colab.research.google.com/</em></a></p><p>Let’s install and import the libraries.</p><p>by using “! pip install library_name” command we can download the libraries.</p><p><strong>Pandas</strong></p><p>PANDAS is one of the most frequently used libraries for data analysis to work with tabular data such as, data manipulation, data pre-processing, or data wrangling.</p><p>Pandas is usually imported under the pd alias. In Python alias are an alternate name for referring to the same thing.</p><p><strong>NumPy</strong></p><p>NumPy (Numerical Python) is a python library. It’s a general-purpose array-processing package that provides high-performance multidimensional objects called arrays and tools for working with them.</p><p>NumPy is also imported under an alias with the np.</p><p>NumPy is used to work with arrays. The array object in NumPy is called ndarray. We can create a NumPy ndarray object by using the array() function.</p><p>Numpy itself in this practice is used to use data from csv for easy visualization.</p><p><strong>Matplotlib</strong></p><p>Matplotlib is a low level graph plotting library in python that serves as a visualization utility. It has powerful yet beautiful visualizations. Most of the Matplotlib utilities lies under the pyplot submodule, and are usually imported under the plt alias.</p><p>Python has many libraries for visualization. One of the most frequently used is matplotlib because it has been around for a long time and is relatively stable in its development. Therefore, matplotlib was chosen to learn visualization in this session.</p><p>Matplotlib itself provides many types of charts ranging from scatter/plot, line, bar, and others.</p><p><em>Let’s get started!</em></p><p><strong>Importing the Libraries</strong></p><pre>import matplotlib.pyplot as plt</pre><pre>import numpy as np <strong><em># linear algebra</em></strong></pre><pre>import pandas as pd <strong><em># data processing, CSV file I/O (e.g. pd.read_csv)</em></strong></pre><p><strong>Reading CSV files using PANDAS</strong></p><p>To begin, we’ll load the dataset.</p><p>I will use <em>google colab</em> to retrieve data via google drive.</p><pre><strong><em># Load the Drive and mount</em></strong></pre><pre>from google.colab import drive</pre><pre><strong><em># This will prompt for authorisation</em></strong></pre><pre>drive.mount(&#39;/content/drive&#39;)</pre><pre><strong><em># After executing the cell above, Drive</em></strong></pre><pre><strong><em># files will be present in :</em></strong></pre><pre>df_event=pd.read_csv(&#39;/content/drive/MyDrive/Peserta/Final Project/All Exercise /Exercise 2/Data/ecommerce_event.csv&#39;)</pre><pre>df_event</pre><pre>##</pre><pre>df_user = pd.read_csv(&#39;/content/drive/MyDrive/Peserta/Final Project/All Exercise /Exercise 2/Data/user_profile.csv&#39;)</pre><pre>df_user</pre><p>We’ve downloaded the dataset. Installed and imported the libraries.</p><p><strong>Data Preparation</strong></p><p>Here we’ve imported data from google drive into the data frame.</p><p>What&#39;s next?</p><p>View the columns and rows of the data, then perform calculations of unique values and data to know better about the features in the dataset.</p><p>Viewing the data and write the observation :</p><p>Attribute .head(), to see the top 5 (default and changeable) data in the dataframe.</p><pre># check for data</pre><pre>df_event.head()</pre><p>Attribute .columns, to find out what columns are available in the dataframe (only used for dataframes).</p><pre># check for columns</pre><pre>df_event.columns</pre><p>Attribute .value_counts(), to find out the number of unique category data in each column.</p><pre># check the number of unique category</pre><pre>df_event.category.value_counts()</pre><p><strong>Questions and Visualizations</strong></p><p>Q — Compare the revenue for each brand in smartphone subcategory using bar chart.</p><p>Firstly, we need to store data in a variable, I choose ‘df_sub’ as a variable. Then filter data with ‘event_type’ = ‘purchase’ to find out revenue for each brand.</p><pre>df_sub = df_event[(df_event[&#39;event_type&#39;]==&#39;purchase&#39;) &amp;</pre><pre>(df_event[&#39;subcategory&#39;]==&#39;smartphone&#39;)</pre><pre>].groupby(&#39;brand&#39;,as_index=False).agg(revenue = (&#39;price&#39;,&#39;sum&#39;)</pre><pre>).sort_values(&#39;revenue&#39;)</pre><pre>df_sub</pre><p>Since we get a new dataframe then we can visualize the data into a bar chart using matplotlib.</p><pre># Create a bar horizontal chart using matplotlib</pre><pre># Making a figure and an axe</pre><pre>fig, ax = plt.subplots(figsize=(13, 5))<br></pre><pre># Plotting data on axes</pre><pre>ax.barh(df_sub[&#39;brand&#39;],df_sub[&#39;revenue&#39;])<br></pre><pre># Changing the x-axis and y-axis labels</pre><pre>ax.set_xlabel(&#39;brand&#39;)</pre><pre>ax.set_ylabel(&#39;revenue&#39;)<br></pre><pre># Add title to axes</pre><pre>ax.set_title(&#39;Revenue per Brand&#39;)</pre><p>Then we get a bar graph like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*37-6Ck8zldI6W51-QE6t5Q.png" /></figure><p>Q — Show the relationship between age and price using scatter plot.</p><p>When we draw a scatter plot, the coordinates of each point are determined by the two columns of the dataframe and a filled circle is used to represent each point. This kind of plot is useful for seeing complex correlations between two variables.</p><p>The Matplotlib module has a method for drawing scatter plots, it needs two arrays of the same length, one for the values of the x-axis, and one for the values of the y-axis.</p><p>But before we go any further, we need to combine the 2 tables to get the values for each axis:</p><pre># check which table contains age and price data</pre><pre># age columns is in user table</pre><pre># while price is in event table<br></pre><pre># let&#39;s merge table to get the data</pre><pre>df_merge_age_price = pd.merge(df_event, df_user, how=&#39;inner&#39;, on=&#39;user_id&#39;)</pre><pre>df_merge_age_price</pre><p>The x array represents the age</p><p>The y array represents the price</p><pre># Create a scatter plot using matplotlib</pre><pre># Making a figure and an axe</pre><pre>fig, ax = plt.subplots(figsize=(10,5))<br></pre><pre># Plotting data on axes<br># ax.scatter(x,y)</pre><pre>ax.scatter(df_merge_age_price[&#39;age&#39;], df_merge_age_price[&#39;price&#39;])<br></pre><pre># Changing the x-axis and y-axis labels</pre><pre>ax.set_xlabel(&#39;ages&#39;)</pre><pre>ax.set_ylabel(&#39;price&#39;)<br></pre><pre># Add title to axes</pre><pre>ax.set_title(&#39;Relationship between Age and Price&#39;)</pre><p>Result :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*2trYccmYPBMKcLo1ZYiwtg.png" /></figure><p>Q — Show the conversion rate (total session purchase/total session view) per day using line chart.</p><p>In this case, we need to add a new column namely conversion rate to be able to display the results</p><p>Firstly, we have to create a data frame for total session of purchase. Then we create a data frame for total session of view and join both of them so we can add a new column.</p><pre># Make DataFrame for total session of purchase</pre><pre>df_purchase = df_event[df_event[&#39;event_type&#39;]==&#39;purchase&#39;].groupby(&#39;event_date&#39;,as_index=False).agg(total_session_purchase = (&#39;user_session&#39;,&#39;nunique&#39;))</pre><pre># then, we make DataFrame  of total session view<br>df_view = df_event[df_event[&#39;event_type&#39;]==&#39;view&#39;].groupby(&#39;event_date&#39;,as_index=False).agg(total_session_view = (&#39;user_session&#39;,&#39;nunique&#39;))</pre><pre># join both of them<br>df_merge_vp = pd.merge(df_purchase, df_view, how=&#39;inner&#39;, on=&#39;event_date&#39;)</pre><pre># make a new columns, conversion rate<br>df_merge_vp[&#39;conversion_rate&#39;] = df_merge_vp[&#39;total_session_purchase&#39;]/df_merge_vp[&#39;total_session_view&#39;]</pre><pre>df_merge_vp</pre><p>We can create a line plot using matplotlib and can use the NumPy module to work with data series/array/list for the values of the x-axis and the values of the y-axis, as follows:</p><pre># Making a figure and an axe<br>fig, ax = plt.subplots(figsize=(15, 5))</pre><pre># Dataset<br>x = np.array(df_merge_vp[&#39;event_date&#39;])<br>y = np.array(df_merge_vp[&#39;conversion_rate&#39;])</pre><pre># Plotting data on axes<br>ax.plot(x, y, linewidth = 3, marker=&#39;o&#39;, markersize=7, color=&quot;green&quot;, label=&#39;user&#39;)</pre><pre># Changing the x-axis label<br>ax.set_xlabel(&#39;Event date&#39;)</pre><pre># Setting x-tick label<br>ax.set_xticklabels(df_merge_vp.event_date, rotation = 45)</pre><pre># Changing y-axis label<br>ax.set_ylabel(&#39;Conversion rate&#39;)</pre><pre># Add a title<br>ax.set_title(&quot;Daily conversion rate&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*DF_onxvBd6IM7T3JqED7Fg.png" /></figure><p>Q — Compare the price distribution from each brand in smartphone subcategory using box plot.</p><p>Box plots are used to visualize summary statistics of a dataset, displaying attributes of the distribution like the data’s range and distribution.</p><p>To create a Box Plot, we’ll need some data to plot. We’ll need to choose a dataset that contains continuous variables as features, since Box Plots visualize continuous variable distribution</p><pre># Filter data in smartphone subcategory<br>df_dist_price_smartphone = df_event[df_event[&#39;subcategory&#39;] == &#39;smartphone&#39;]</pre><pre># Plotting data with price and brand parameters<br>df_dist_price_smartphone.boxplot(column =[&#39;price&#39;], by = [&#39;brand&#39;], figsize =(15,5))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*3YDxXsYdUp2FK1cHTC9NCg.png" /></figure><p>Hope you found it helpful! Thanks for reading!<br>Let’s connect on <a href="https://www.linkedin.com/in/alfianaramdhan?lipi=urn%3Ali%3Apage%3Ad_flagship3_profile_view_base_contact_details%3BTsnbEmBZRtaNsZg0J1IHXQ%3D%3D">Linkedin</a>!</p><p><strong>References :</strong></p><p><a href="https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.boxplot.html">https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.boxplot.html</a></p><p><a href="https://medium.com/@lamsampathkumar0/eda-exploratory-data-analysis-project-using-python-de90cbf4e128">https://medium.com/@lamsampathkumar0/eda-exploratory-data-analysis-project-using-python-de90cbf4e128</a></p><p><a href="https://www.w3schools.com/python/numpy/default.asp">https://www.w3schools.com/python/numpy/default.asp</a></p><p><a href="https://www.w3schools.com/python/pandas/pandas_getting_started.asp">https://www.w3schools.com/python/pandas/pandas_getting_started.asp</a></p><p><a href="https://www.w3schools.com/python/python_ml_scatterplot.asp">https://www.w3schools.com/python/python_ml_scatterplot.asp</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74e7054cf915" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[7 SQL Queries You Should Know as Data Analyst]]></title>
            <link>https://medium.com/@alfiramdhan/7-sql-queries-you-should-know-as-data-analyst-6a16602fffbe?source=rss-82c640d9f481------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a16602fffbe</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[query]]></category>
            <category><![CDATA[data-analyst]]></category>
            <dc:creator><![CDATA[Alfiramdhan]]></dc:creator>
            <pubDate>Thu, 21 Jul 2022 14:49:37 GMT</pubDate>
            <atom:updated>2022-08-01T08:16:44.521Z</atom:updated>
            <content:encoded><![CDATA[<p>The Most Used SQL Queries with Examples</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*3j1oChMnqTO7bRx3SBzxGQ.jpeg" /></figure><h3>What is SQL?</h3><p>SQL, which stands for <em>Structured Query Language</em>, is a standard computer language used to interact with a database system — or rather a relational database management system. So, users can add, modify, update, search and delete data from a database system using SQL.</p><p>Nowadays, we all know how data important is. In this post, we will see the most common SQL queries with study cases.</p><p><em>Note: All the queries are written in </em><a href="https://www.w3schools.com/sql/"><strong><em>https://www.w3schools.com/sql/</em></strong></a><em>.</em></p><p><strong><em>Let’s get started!</em></strong></p><p><strong>1.</strong> <strong>Selecting Distinct and Aggregate Functions</strong></p><p><strong>1.1</strong> <strong>Select Distinct</strong></p><p>Inside a table, a column often contains many duplicate values; and sometimes you only want to list the different (distinct) values. To eliminate duplicate data, we can use the <strong>select distinct</strong> statement.</p><p>With <strong>select distinct</strong>, the same or duplicate data will be eliminated and only unique data will be displayed.</p><p>Syntax :</p><pre>SELECT DISTINCT column1, column2,...<br>FROM table_name;</pre><p><strong>1.2 Aggregate Functions</strong></p><p>Aggregate function is used to perform calculations on a group of values. Various aggregate functions such as <strong>sum(), count(), avg(), max(), and min()</strong>, here are the details :</p><p>The <strong>min() </strong>function returns the smallest value of the selected column.</p><p>The <strong>max()</strong> function returns the largest value of the selected column.</p><p>The <strong>count() </strong>function returns the number of rows that matches a specified criterion.</p><p>The <strong>avg()</strong> function returns the average value of a numeric column.</p><p>The <strong>sum() </strong>function returns the total sum of a numeric column.</p><p>Syntax :</p><pre>SELECT &#39;aggregate function&#39;(column_name)<br>FROM table_name;</pre><p><strong>Demo Database</strong></p><p>Let’s say we have 2 tables that contain sales data in an e-commerce, I call them ecommerce_event and user_profile table.</p><p>The following is the contents of the ecommerce_event table,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*SmODN3Nb4iQAYFGy9SrDMQ.png" /><figcaption>Table. ecommerce_event</figcaption></figure><p>This table contains product information and records of events carried out by the user along with the date info.</p><p>Then the following is the contents of the user_profile table, which contains a record of user information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*uw5ChM8BE9CGDQw6cKfcLA.png" /><figcaption>Table. user_profile</figcaption></figure><p><em>Now let’s explore those two tables to get sales information!</em></p><p><strong>Example 1</strong></p><p>From the “ecommerc_event<em>” </em>table, write a SQL query to output:</p><p>1. Total unique of user_session</p><p>2. Lowest, highest, and average <em>price</em></p><p>With criteria “event_type”<em> </em>is view, and brand except apple and samsung.</p><p>Before we answer that, let’s break down the problem we really need to pay attention to there:</p><p>a. Pick the columns that we need to show the data, which are the user_session and price columns;</p><p>b. A column often contains many duplicate values, so we can use <strong>count distinct statement on </strong>user_session column to get amount of unique data;</p><p>c. In order to get output on point b, we can aggregate the value of price column using <strong>avg(), max(), and min() function</strong>;</p><p>d. Then filter the data using <strong>where</strong> clause based on the criteria requested.</p><p>Query :</p><pre>SELECT<br>    COUNT(DISTINCT user_session) as total_unique_user_session,<br>    MIN(price) as lowest_price,<br>    MAX(price) as highest_price,<br>    ROUND(AVG(price),2) as average_price<br>FROM<br>    ecommerce_event<br>WHERE<br>    event_type = &#39;view&#39; AND brand NOT IN (&#39;apple&#39;,&#39;samsung&#39;);</pre><p>Result :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*S8NPUUfH6nv4p3fCoRLPeg.png" /></figure><p>So the results throughout October 2019, were 12,550 sessions followed by the lowest price of 0.88 then the highest price of 2,574.07 and the average price of 246.25.</p><p><strong>2.</strong> <strong>Where Statement</strong></p><p>The <strong>where</strong> clause is used to filter records. It is used to extract only those records that fulfill a specified condition.</p><p>Syntax :</p><pre>SELECT DISTINCT column1,column2,..<br>FROM table_name<br>WHERE conditions;</pre><p><strong>Example 2</strong></p><p>Write a SQL query to output total unique product. Filter brand which start with ‘a’ or ‘k’ letter, and date after ‘2019–10–04’</p><p>Let’s break down the problem. First, we need to show unique number of product. So we can use <strong>count distinct</strong> statement on product_id column and use <strong>where</strong> clause to filter some criteria,</p><p>Query :</p><pre>SELECT<br>    COUNT(DISTINCT product_id) as total_product<br>FROM<br>   ecommerce_event<br>WHERE (brand LIKE &#39;a%&#39; OR brand LIKE &#39;k%&#39;)<br>     AND event_date &gt; &#39;2019-10-04&#39;;</pre><p>And the result show that total of unique product throughout October 2019 amounted to 891:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*39-fyQFTTat4xygQdJHl5A.png" /></figure><p><strong>3.</strong> <strong>Group by and Order by Clause</strong></p><p>In order to group data in SQL, we use the <strong>group by</strong> statement. The <strong>group by</strong> statement will group data with the same value into one group, and by using an aggregate function such as (COUNT, MAX, MIN, SUM, AVG) we can perform aggregation for each group or groups that are formed. While <strong>order by</strong> keyword is used to sort the result-set in ascending or descending order.</p><p><em>Important things to note are:</em></p><p>a. <strong>Group by</strong> is used with <strong>select</strong>, meaning that the columns used in the <strong>group by</strong> statement also need to be placed in the <strong>select</strong>.</p><p>b. <strong>Group by</strong> is placed after <strong>where</strong>, but if you don’t use <strong>where</strong> then it is placed immediately after <strong>from</strong>.</p><p>c. If using <strong>order by</strong>, then <strong>group by</strong> is placed before <strong>order by</strong></p><p>Syntax :</p><pre>SELECT column_name(s)<br>FROM table_name<br>WHERE condition<br>GROUP BY column_name(s)<br>ORDER BY column_name(s);</pre><p><strong>Example 3</strong></p><p>Write a SQL query to output <em>total unique product </em>and<em> total unique user, </em>for every order date<em>.</em> Only show the date above 04 august 2019, and sort the result by the latest date.</p><p>In this case, we need to use <strong>count distinct</strong> statement on product_id and user_id columns to get unique numbers and also use <strong>group by</strong> statement which will group rows having the same value into summary rows.</p><p>Query :</p><pre>SELECT<br>    event_date as order_date,<br>    COUNT(DISTINCT product_id) as total_unique_product,<br>    COUNT(DISTINCT user_id) as total_uniques_user<br>FROM<br>    ecommerce_event<br>WHERE<br>     order_date &gt; &#39;2019-08-04&#39;<br>GROUP BY order_date<br>ORDER BY order_Date DESC;</pre><p>Result :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*fRGRFaMNMcOpWFQ52FFMtw.png" /></figure><p><strong>4.</strong> <strong>Having Clause</strong></p><p><strong>Having</strong> clause is used instead of <strong>where</strong> when using <strong>group by</strong> whose data is aggregated.</p><p>Syntax :</p><pre>SELECT column_name(s)<br>FROM table_name<br>WHERE condition<br>GROUP BY column_name(s)<br>HAVING condition<br>ORDER BY column_name(s);</pre><p><strong>Example 4</strong></p><p>From the question of example 3, filter only dates that have total unique product more than 500.</p><p>Similar to the previous, in this case we only need to add a <strong>having</strong> clause to the aggregate data.</p><p>Query :</p><pre>SELECT<br>    event_date as order_date,<br>    COUNT(DISTINCT product_id) as total_unique_product,<br>    COUNT(DISTINCT user_id) as total_uniques_user<br>FROM<br>    ecommerce_event<br>WHERE<br>     order_date &gt; &#39;2019-08-04&#39;<br>GROUP BY order_date<br>HAVING total_unique_product &gt; 500<br>ORDER BY order_Date DESC;</pre><p>Result :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*V3Aednmw6LclMJa3exDiXA.png" /></figure><p><strong>5.</strong> <strong>Join Clause</strong></p><p>A<strong> join</strong> clause is to join two or more different tables in the database. Well, this <strong>join</strong> can only be done if the tables have the same column key. In SQL, there are several types of <strong>join</strong>, namely: <strong>inner join</strong>, <strong>left join</strong> or <strong>right join</strong>. Each join type has a different purpose and query result.</p><p>Syntax :</p><pre>SELECT <em>column_name(s)</em><br>FROM <em>table1</em><br>JOIN <em>table2<br></em>ON <em>table1.column_name </em>=<em> table2.column_name</em>;</pre><p><strong>Example 5</strong></p><p>From the ecommerc_event and user_profile table, which gender has more sessions in October 2019?</p><p>Let’s take a moment. In this case we need to combine 2 tables to get information on which gender has the most sessions during October 2019. Firstly, we need to find the primary key and foreign key of each table. These key are useful for connecting the two tables so that we can get the table information.</p><p>Notice that the user_id column in the ecommerce_event table refers to the user_id column in the user_profile table. So the relationship between the two tables above is the user_id column.</p><p>Then we can create the following SQL statement using Inner Join that selects records that have matching values in both tables.</p><p>Query :</p><pre>SELECT<br>    gender,<br>    COUNT(DISTINCT user_session) as total_sessions<br>FROM<br>    ecommerce_event as e<br>INNER JOIN user_profile as u<br>ON e.user_id = u.user_id<br>WHERE<br>     event_date BETWEEN &#39;2019-10-01&#39; AND &#39;2019-10-30&#39;<br>GROUP BY gender<br>ORDER BY total_sessions DESC;</pre><p>Result :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*j8luMtSlufDRlKktPFgTIQ.png" /></figure><p>As we can see throughout October 2019, Male has more sessions than Female, with the total sessions were 9747.</p><p><strong>6.</strong> <strong>Case When Clause</strong></p><p>The <strong>case</strong> statement goes through conditions and returns a value when the first condition is met (like an if-then-else statement). So, once a condition is true, it will stop reading and return the result. If no conditions are true, it returns the value in the <strong>else</strong> clause. If there is no <strong>else</strong> part and no conditions are true, it returns null.</p><p>Syntax :</p><pre>CASE<br>    WHEN <em>condition1</em> THEN <em>result1</em><br>    WHEN <em>condition2</em> THEN <em>result2</em><br>    WHEN <em>conditionN</em> THEN <em>resultN</em><br>    ELSE <em>result</em><br>END;</pre><p><strong>Example 6</strong></p><p>From the ecommerce_event and user_profile table, is it true that iphone has more dominated by female and samsung dominated by male?</p><p>The <strong>case</strong> statement is used to implement the logic where you want to set the value of one column depending upon the values in other columns. In this case, we want to know which brand (iphone, Samsung) has more dominated by gender. So we set <strong>case</strong> statement goes through ‘brand’ conditions and once the condition is true, it will return the result. Here are the code,</p><p>Query :</p><pre>SELECT<br>     gender,<br>     COUNT(DISTINCT CASE WHEN brand = &#39;apple&#39; THEN e.user_id END)<br>     as apple,<br>     COUNT(DISTINCT CASE WHEN brand = &#39;samsung&#39; THEN e.user_id END)<br>     as samsung<br>FROM<br>    ecommerce_event as e<br>INNER JOIN user_profile as u<br>ON e.user_id = e.user_id<br>GROUP BY gender;</pre><p>Through following table, we can see that Male dominated apple while samsung was dominated by Female,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*vHSNjw7Y0xS58d103H5dPA.png" /></figure><p><strong>7.</strong> <strong>Subqueries</strong></p><p>A subquery is a SQL query nested inside a larger query. A subquery may occur in:</p><p>a SELECT clause</p><p>a FROM clause</p><p>a WHERE clause</p><p><strong>Example 7</strong></p><p>Calculate the daily average revenue per user (Revenue/ # users) for date with revenue higher than 3000.</p><p>In order to solve the problem, we require two queries. One query returns the revenue and total unique user, then a second query identifies the daily average revenue per user. Firstly,</p><p>First query :</p><pre>SELECT<br>     DATE(event_date) as data_date,<br>     ROUND(SUM(price),2) as revenue,<br>     COUNT(DISTINCT e.user_id) as unique_user<br>FROM<br>    ecommerce_event as e<br>INNER JOIN user_profile as u<br>ON e.user_id = u.user_id<br>WHERE event_type = &#39;purchase&#39;<br>GROUP BY data_date<br>ORDER BY data_date;</pre><p>Query result :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*oQwJMQWaawKiHMoB-92L1A.png" /></figure><p>Using the result of this query, here we have written another query to identify the daily average revenue per user, for date with revenue higher than 3000. Or we can combine the above two queries by placing one query inside the other. The subquery (also called the ‘inner query’) is the query inside the parentheses. See the following code and query result :</p><pre>WITH daily_data AS(<br>  SELECT<br>     DATE(event_date) as data_date,<br>     ROUND(SUM(price),2) as revenue,<br>     COUNT(DISTINCT e.user_id) as unique_user<br>  FROM<br>     ecommerce_event as e<br>  INNER JOIN user_profile as u<br>  ON e.user_id = u.user_id<br>  WHERE event_type = &#39;purchase&#39;<br>  GROUP BY data_date<br>  ORDER BY data_date<br>)</pre><pre>SELECT<br>    data_date,<br>    ROUND(revenue/unique_user,2) ARPU<br>FROM<br>    daily_data<br>WHERE<br>    revenue &gt; 3000;</pre><p>Final result :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*Qi-PIe-Hr15X9er8dvQBog.png" /></figure><p>These are the queries that are used commonly by data professionals.</p><p>Hope you found it helpful! Thanks for reading!<br>Let’s connect on <a href="https://www.linkedin.com/in/alfianaramdhan?lipi=urn%3Ali%3Apage%3Ad_flagship3_profile_view_base_contact_details%3BTsnbEmBZRtaNsZg0J1IHXQ%3D%3D">Linkedin</a>!</p><p>Not sure what to read next? please visit the <a href="https://medium.com/@alfianaramdhan02/basic-python-work-with-pandas-numpy-and-matplotlib-74e7054cf915">Basic Python : Work with Pandas, Numpy and Matplotlib</a> and <a href="https://medium.com/@alfiramdhan/dashboard-with-google-data-studio-dad18371b9a">Dashboard with Google Data Studio</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a16602fffbe" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>