<?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 Michael Rahardja on Medium]]></title>
        <description><![CDATA[Stories by Michael Rahardja on Medium]]></description>
        <link>https://medium.com/@mikerhrdja?source=rss-d0dcf90dce5c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*O3MqUlOnIaHwiBNRGq_YHg.jpeg</url>
            <title>Stories by Michael Rahardja on Medium</title>
            <link>https://medium.com/@mikerhrdja?source=rss-d0dcf90dce5c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 12:22:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mikerhrdja/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[Creating an inspirative Data Visualization through Looker Studio]]></title>
            <link>https://medium.com/@mikerhrdja/creating-the-inspirative-data-visualization-through-looker-studio-358d6b8f4d0b?source=rss-d0dcf90dce5c------2</link>
            <guid isPermaLink="false">https://medium.com/p/358d6b8f4d0b</guid>
            <category><![CDATA[google-data-studio]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[looker-studio]]></category>
            <dc:creator><![CDATA[Michael Rahardja]]></dc:creator>
            <pubDate>Wed, 15 Mar 2023 12:40:30 GMT</pubDate>
            <atom:updated>2024-11-24T17:48:46.236Z</atom:updated>
            <content:encoded><![CDATA[<h3>Hotel Bookings Data Visualization through Looker Studio</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZuZt-24P_Ojbf3pL" /><figcaption>Photo by <a href="https://unsplash.com/@lukechesser?utm_source=medium&amp;utm_medium=referral">Luke Chesser</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Hi again! Back with me for another article. In this article, we are going to explain how to visualize your data in a creative and inspirative way through Looker Studio. Before we started from the core points of the content, let us begin with some brief explanations about visualizing our data to the readers and/or customers in a real-life business case. According to <a href="https://www.ibm.com/topics/data-visualization#:~:text=the%20next%20step-,What%20is%20data%20visualization%3F,that%20is%20easy%20to%20understand.">IBM</a>, data visualization is the representation of data through the usage of common graphics, such as charts, plots, or infographics that display information as the media to communicate data-driven insights and relationships easily. Then, from <a href="https://www.techtarget.com/searchbusinessanalytics/definition/data-visualization#:~:text=The%20main%20goal%20of%20data,information%20visualization%20and%20statistical%20graphics.">TechTarget</a>, the main target of data visualization is really important to make it easier to identify patterns, trends, and outliers in large data sets to give insightful information about the data. Visualization of data is a vital step for almost every analytical job, from Data Scientist, Data Analyst, Business Analyst, even for HR or Consultants that require big data project handling. Like most companies, particularly in Indonesia, data would play the most important role to determine the next step of their company and helping the stakeholders to make a proper decision on their business.</p><h4>Purposes of Data Visualization</h4><p>From IBM, data visualization is divided into 4 (four) purposes, which contain:</p><p>A. Idea generation: Data visualization is commonly used to spur idea generation across teams by supporting the collection of different perspectives and highlighting common concerns and helping to set the foundation within the project to ensure that the team is aligned on the problem that they’re looking to address for key stakeholders.</p><p>B. Idea illustration: Data visualization for idea illustration assists in conveying an idea, and it is commonly used in learning settings, such as tutorials, certification courses, and centers of excellence, but it can also be used to represent organization structures or processes, facilitating communication between the right individuals for specific tasks.</p><p>C. Visual discovery: Visual discovery helps data analysts, data scientists, and other data professionals identify patterns and trends within a dataset, to support the subsequential storytelling on the discovered insights.</p><p>D. Data visualization: Critical steps to capture key concepts, trends, and hidden relationships within this unstructured data.</p><h4>Looker Studio</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CsXexHMpIH80oaI6TouDLA.png" /><figcaption>Looker Studio (formerly known as Google Data Studio) (image source from)</figcaption></figure><p>Based on the definition from <a href="https://support.google.com/looker-studio/answer/6283323?hl=en#:~:text=Data%20Studio%20is%20a%20free,fully%20customizable%20dashboards%20and%20reports">Google</a>, Looker Studio, formerly known as Google Data Studio, is a free tool that turns your data into informative, easy-to-read, easy-to-share, and fully customizable dashboards and reports. As referred by <a href="https://www.seerinteractive.com/insights/google-data-studio-whats-working-whats-missing">Seer</a>, Looker Studio has access to some key features:</p><ul><li>Live data connection and access to over 220 connectors</li><li>Full control over customization of reports and visuals, including adding as many pages or charts as needed</li><li>Dynamic controls with the report and page-level filters</li><li>Advanced formulas such as calculated metrics and calculated fields</li></ul><h4>Accessing the Looker Studio</h4><p>To utilize deeper data visualization, go to <a href="http://lookerstudio.google.com/">lookerstudio.google.com</a> and log into your Google account. Then, to create a new report, you could just click the <em>Blank Report</em> on the left side of the homepage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*hIBFQVEiQqJiT-09r8wRqQ.jpeg" /></figure><p>Right after clicking the <em>Blank Report</em>, you are allowed to select your data source by clicking ‘Add Data’ on the toolbars. represented with an image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BCd-uoBLGVXodjb-8npj4w.jpeg" /><figcaption>Toolbars on Looker Studio</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M7Ihz0yG5pIBtKgqUisc_g.jpeg" /></figure><p>Refers to the second image above, you could select your data source by its format. Since in this article, the dataset was in the XLSX format, the closest option would be on Google Sheets.</p><h4>However, before selecting the data from Google Sheets, ensure that your original data had been saved into the Sheets format. Hence, the dataset you pick would appear once you click Google Sheets from the image above.</h4><p>After you did the conversion phase, you could find your data in the spreadsheet selections.</p><p>Since we are going to use the downloaded and cleaned <em>‘Hotel Booking Demand Dataset’</em> from Github, including the combination of the country data, then you can select the corresponding dataset, choose the worksheet, and make sure the header is selected before visualization use. And, ta-da! You are now ready to utilize any fields and/or parameters for your own customized data visualization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zHKW-ATWRPpQBKiDKqhK1w.jpeg" /><figcaption>Choosing a dataset for visualization</figcaption></figure><p>On the right side of the Looker sheet, you could see any fields of your dataset for verifications, and chart style whether you had already clicked <em>‘Add chart’</em> from the toolbars.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*6n1EXb5TLxSEO7v8paesJA.jpeg" /><figcaption>Chart and data toolset</figcaption></figure><p>Besides those features, Looker Studio also allows the user to modify the visualization through <em>‘Themes and layout’ </em>on the toolbar. It would display as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/1*DULnf77RHe9IcB8UwrRWjw.jpeg" /></figure><p>There are a lot of options provided for the themes and layouts. So, you could create your comfort zones for visualizing your data.</p><p>And now, we are going to visualize our data by 6 (six) cases inside the hospitality world below, which are the hotel bookings in this context.</p><h3>Case 1</h3><blockquote>How many total bookings had been made for each hotel type? Which one had more bookings? Give insights into the visualization.</blockquote><p>As previously said above, we will use the <a href="https://github.com/rfordatascience/tidytuesday/tree/master/data/2020/2020-02-11"><em>‘Hotel Booking Demand Dataset’</em></a> that could be downloaded right here. From the stated question, we would like to find out which hotel had more bookings with the total value of bookings with the proper fields below:<br>A. Reservation dates <em>(reservation_status_date)</em><br>B. Hotel types <em>(hotel)</em><br>C. Booking record <em>(Record Count)</em></p><p>By taking those fields, we could arrange them into the chart toolbox below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/232/1*a47vDBRxMjcTM87-s2wHTQ.jpeg" /></figure><p>Before plotting the chart based on the fields above, we should acknowledge the data types and the utilization based on the provided setup above. From the chart toolbox above, the setup had been settled right after we added the chart. However, understanding the proper data fields on each setup is the most important thing to do. Because we want to look at total bookings from each hotel type, therefore we should drop the ‘hotel’ data field into the Dimension setup. Then, for this question, we are using the bar graph for easier visualization. Put on notice that you could modify your graph on your own by clicking the ‘Chart’ box. And here is the plotted graph below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*kVBvRHrqYg77QyjmovsfgQ.jpeg" /></figure><p>From this graph, we could state that total bookings at City Hotel were twice the total bookings from Resort Hotel with approximately 80,000 bookings.</p><h3>Case 2</h3><blockquote>Since both hotels originated from Portugal, display the visualizations of the comparison between local tourists from Portugal and inbound tourists who were not canceled their bookings, and explain the insight from the visualizations.</blockquote><p>To answer this question, we should limit the data only to the not canceled bookings from the <em>‘is_canceled’</em> field based on the Data box and build a new field named <em>‘Marketshare’</em> within the formulas below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*W5itPl-lx-pnBQFqqRPXOw.jpeg" /></figure><p>From the formula, we use the CASE WHEN clause to differentiate between the ‘Local Market’ variable for Portugal tourists and the ELSE clause for the other tourists. After that process, we should put on the Dimension setup, so we could see the comparison for both variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/236/1*SoR06HgyVfBPqJQQPciZjg.jpeg" /></figure><p>Since we would take data values only for the not canceled bookings, then we should add a filter by clicking ‘Add Filter’ at the Filter setup inside the Chart toolbox. Then named it a <em>‘Non canceled filter’</em> by modifying the parameters. By the restrictions above, we put the ‘is_canceled’ value equal to 0, which means the data would be filtered only inside the terms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*l51zJVrAqpEYKcoE7wW7Rw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/231/1*JJddvmNtbg_pWcOVLN-4QA.jpeg" /><figcaption>Non canceled filter</figcaption></figure><p>With all data fields applied to the respective setup, here are the results in the bar graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*lZqaWKwJaDE2jTLh0qBfpw.jpeg" /></figure><p>From the bar graph above, we could state that <strong>Inbound Tourism had around 2.6 times more bookings than Local Market, within non-cancellation terms applied</strong> to the setup.</p><h3>Case 3</h3><blockquote>What are the patterns in the weekly ADR (Average Daily Rate) of both hotels? Are both hotels had fluctuating ADRs in the same period of time? Explain your insight related to the occasions.</blockquote><p>According to <a href="https://www.cvent.com/en/blog/hospitality/hotel-adr-average-daily-rate">Cvent</a>, ADR (Average Daily Rate) is the measurement of the average revenues for each occupied guest room per day. ADR includes the promotion, discount rates, best available rates, group rates, business rates, and the other price packages per night in a certain hotel. With ADR, a hotel could track the fluctuations for a certain time range and set rate goals to increase the revenue of the hotel and provide information for better decision-making for the hotel.</p><p>Common reasons for hotel ADR fluctuations would be as follows:</p><ul><li>Special events and blackout dates</li><li>High corporate travel</li><li>Group rates</li><li>High demand and <a href="https://www.cvent.com/en/blog/hospitality/what-is-shoulder-season">shoulder seasons</a></li><li>Climate and other weather-related complications</li></ul><p>For answering this case, we should take the filter for the <em>‘reservation_status_date’</em> field for both Date Range Dimension and the Dimension setup by clicking the pencil logo, then search ‘Date and Time’ and select ‘ISO Year Week’ as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/313/1*aJPCCTXUWXpPin_UB97JCA.jpeg" /></figure><p>Thus, after applying the time range by picking a hotel for dimension breakdown and the ‘adr’ field as the metric with AVG function and dimension breakdown, the result would be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/230/1*TLuB-G_Bs42oR_t7SS_y6A.jpeg" /></figure><p>After the fields are ready with the support of <em>‘Non canceled filter’ </em>in the Filter setup from the previous case, then we applied the line graph to visualize the fluctuation of the ADRs of both hotels.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*n6_9l7XpfRPbYrikn5gw8A.jpeg" /><figcaption>ADRs comparison for both hotels</figcaption></figure><p>As seen on the graph, the ADRs from both City Hotel and Resort Hotel were fluctuating. However, the City Hotel was more stable in ADRs than the Resort Hotel which sometimes reach the highest ADRs and plunged in the following weeks on Week 33 of 2016 and Week 32 of 2017. At the same time, both hotels reach their highest ADRs on Week 32 of 2017, in which the City Hotel generates $146.9, while the Resort Hotel generates $212.03 in the same week.</p><h3>Case 4</h3><blockquote>What are the cancelation rates for both hotels? Which hotels had the highest cancelation rates? Explain your insight related to the occasions.</blockquote><p>Cancellation rates are really essential to many hotels across the world. Based on <a href="https://www.hotelminder.com/everything-you-need-to-know-about-hotel-cancellations">HotelMinder</a>, cancelation matters because of several reasons below:</p><p>a. Guest Cancellations lowers occupancy rates &gt;&gt; revenue decreases<br>b. Regular Cancellations drop the rating of the hotel<br>c. Creates additional work and stress</p><p>And, there are 3 (three) main factors that made the cancellations occur:</p><p>a. Multiple bookings at one-time.<br>b. Fraudulent bookings<br>c. “Last-minute” call</p><p>Back again, for visualizing the occurred case, we should know and develop a syntax for the cancelation condition by creating a new field below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*9O2aTbOc6WKXVjYaTNQsWA.jpeg" /></figure><p>After the first new field had been created, then use that field for the second new field named <em>‘Cancelation Rate’</em> below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*Uvvwsl8anNGRVWgeeqDBEw.jpeg" /></figure><p>Through those new fields, we could apply the <em>‘Cancelation Rate’ </em>to the chart setup below, with the <em>‘arrival_date’ </em>selected for both time dimension setups, filtered into Year Month, and broken down to the hotel types.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/229/1*-xgNskSfr3-4RMBlw4kSkg.jpeg" /></figure><p>Here is the graph that could be displayed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*1Fi0_3SSmtWSqububZ_Sdg.jpeg" /><figcaption>Cancelation rates of both hotels</figcaption></figure><p>From the line graph above of the overall cancelation rates, <strong>the City Hotel had the highest cancelation rates, which occurred in June 2015</strong>.</p><h3>Case 5</h3><blockquote>Indicate the canceled bookings for each market segment and locate which one had the highest rates of cancelations. Give insight related to the case. (Note: Eliminate the ‘Undefined’ market segment)</blockquote><p>To answer this question, there are 5 (five) fields required for the visualization followed by the chart setups.</p><p>A. Reservation dates <em>(reservation_status_date)</em> &gt;&gt; Date Range Dimension<br>B. Market segments <em>(market_segment)</em> &gt;&gt; Dimension<br>C. Booking record <em>(Record Count)</em> &gt;&gt; Sort<br>D. Canceled Booleans <em>(is_canceled)</em> &gt;&gt; Metric<br>E. Customer IDs <em>(id)</em> &gt;&gt; Metric</p><p>The reason why the ‘<em>market_segment’ </em>used in the Dimension setup is that we would like to know how is the cancelation rates throughout segmental markets. Moreover, the <em>‘id’</em> and the <em>‘is_canceled’</em> metrics in the SUM function are required to indicate the total occurred cancelations. Although those data fields are applied to each chart setup, we should add a filter called <em>‘Undefined’</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/231/1*0zytmJy6lA2fW-S7XKvDcg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*xM-hzz9L794QG6_54AjRIw.jpeg" /><figcaption>Conditional settings for both filters</figcaption></figure><p>For the filtering<em> </em>field, we should exclude the <em>‘Undefined’ </em>segment from the ‘<em>market_segment’</em> data field. When the filter is applied, then we could totally set up those fields into a chart.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/235/1*-H3DBR0Mu55LIkkvVmu7lw.jpeg" /></figure><p>To accommodate both metrics, we select the Combo chart of line and column graphs, in which the <em>‘is_canceled’ is </em>represented in the bar graph and<em> </em>the<em> ‘Cancellation Rate’</em> in the line graph based on the segments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*LuHlkldTo678PXorqm6Uag.jpeg" /></figure><p>From the chart above, <strong>the ‘Online TA’</strong> segment <strong>leads the most cancelations</strong>, but <strong>the ’Groups’</strong> segment had <strong>the most percentage of cancelations</strong>.</p><h3>Case 6</h3><blockquote>Build one other data visualization from the same dataset above.</blockquote><p>For this case, we decide to build a <strong>total number of visitors by each country, in which they all reserved and stayed in the hotel</strong>. It means that all visitors are committed to the reservations. There are 2 (two) main data fields required for the visualization and the setups.</p><p>A. Reservation dates <em>(reservation_status_date)</em> &gt;&gt; Date Range Dimension<br>B. Origins <em>(country)</em> &gt;&gt; Dimension<br>C. Booking record <em>(Record Count)</em> &gt;&gt; Metric</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/229/1*dhvZso5ZjyDC9lJZcrPSXg.jpeg" /></figure><p>By applying those setups, we pick up the bar graph to visualize the data below, with <em>‘Non canceled filter’ </em>in the Filter setup from case number 2 and number 3 below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*4nUztsRapfLYREDqE_ob-Q.jpeg" /></figure><p>As seen on the graph, <strong>Portugal dominates with 21,701 visitors</strong>, the most from all countries in the graph, followed by visitors from the UK and France.</p><p>That is all from this article on Data Visualization. Perhaps your insight increased, especially in solving business cases through visual aspects. Thank you, and see ya at the next one. Auf Wiedersehen!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=358d6b8f4d0b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hotel Customers Analysis using Python]]></title>
            <link>https://medium.com/@mikerhrdja/python-for-data-analysis-purposes-cd1b6e35aeef?source=rss-d0dcf90dce5c------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd1b6e35aeef</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Michael Rahardja]]></dc:creator>
            <pubDate>Wed, 15 Mar 2023 12:05:46 GMT</pubDate>
            <atom:updated>2024-11-24T17:47:41.623Z</atom:updated>
            <content:encoded><![CDATA[<h3>Hotel Bookings Analysis using Python</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*eivOEMIkvob5FA0j8ZZamg.png" /><figcaption>Python image (Source: Google)</figcaption></figure><p>Nowadays, Python is widely used for many purposes related to data manipulation and analysis, and recently the most popular programming language in the world. On the other hand, Python has great versatility in its utilization and is useful for any coding type, such as web development, game development, and even for an AI system, Computer Vision, or Engineering purposes to create algorithms in robotics. Based on <a href="https://www.forbes.com/sites/forbestechcouncil/2022/12/28/what-your-software-partner-should-know-the-top-programming-languages-of-2023/?sh=531fb3a9182b">Forbes.com</a>, Python would be considered the most in-demand programming language in 2023. Python is also really friendly for beginners whose eager to learn programming compared to others like Java, C++, or C#. Hence, learning Python is an incredible deal to learn and master in it.</p><p>In this article, we would use Python for data analysis from hotel bookings demand datasets in Portugal and visualize them based on the selected parameters. For the platform itself, we are going to use Google Colab which is free of charge and available online. Colab also provided sufficient 12 GB RAM size, and it helps you to either learn or work inside the Data Science universe with good features and tons of libraries provided.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hVtKhCBcDg84nf1OsG2iLA.png" /><figcaption>Google Colaboratory (Source: Wikimedia)</figcaption></figure><p>So, we are going to solve questions related to the given datasets from MySkill in Python in terms of both data analysis and visualization.</p><p>In this article, only one hotel booking dataset to utilized. If you want to learn more about the dataset, you could click this <a href="https://github.com/rfordatascience/tidytuesday/tree/master/data/2020/2020-02-11">download link</a>. Whether you are curious about the full article, just download that article by clicking the link <a href="https://doi.org/10.1016/j.dib.2018.11.126">here</a>.</p><h3><strong>Importing libraries and dataframes</strong></h3><p>Before entering the analysis process through Python, first we need to prepare our necessary libraries:</p><pre>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br>import re<br>sns.set()</pre><p>And now, we would briefly explain each of the libraries below:<br>a. Pandas (pd): Library in Python for data analysis<br>b. NumPy (np): Numerical computational library in Python<br>c. Matplotlib (plt): A plotting library in Python extensive for data visualization as the MATLAB replacement that supports many formats<br>d. Seaborn (sns): Extended data visualization library based on matplotlib that prevents overlapped plots.<br>e. <a href="https://www.tutorialspoint.com/python/python_reg_expressions.htm">RegEx</a>: This library was imported to help users to match or find other strings or sets of strings containing specified search patterns in a sequence of characters.</p><p>Up next, the datasets would be imported into the Python environment</p><pre>df_hotels = pd.read_csv(&#39;https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2020/2020-02-11/hotels.csv&#39;)<br>df_hotels.head()</pre><p>In those lines, we call the comma-separated file (.csv) file through a GitHub URL, and it is possible to directly set the dataset up to Python. Besides, the dataset themselves had been cleaned before being used for analysis and stored as df_hotels variable. However, the dataset requires a unique identifier. Thus, we should add the reset_index().rename() to reset the index into a new column by keeping the old values in the syntax below:</p><pre>df_hotels = df_hotels.reset_index().rename(columns={&#39;index&#39;:&#39;id&#39;})<br>df_hotels.head()</pre><p>Then, we should check all columns inside the dataset followed by the data types with the syntax below:</p><pre>df_hotels.dtypes</pre><p>Hence, we would obtain the results as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/1*35ta4bEQhcV751Pya7SKyg.jpeg" /></figure><p>From the details above, there are 33 (thirty-three) columns including the id column and ready to be manipulated and analyzed.</p><h3><strong>Number 1</strong></h3><blockquote>Build a function with:<br>1 argument in dataframe form to check the datatypes, null values, percent null values, and the total unique values on each column inside the dataframe</blockquote><p>Each function of Python always started with def followed by the function_name(value) with the colon (:) to begin the inner codes for the related function. For answering this question, we need to develop a new table within the parameters above inside for loopings. To identify all the datatypes, null values, percentages of null values, and total unique values, we could use those commands [.dtype, .isna().sum(), and .nunique()]. For the percentages of the null values, we could use it inside the round() divided by the data length of the dataframe (len(df)), before checking all the values right after the function has been executed.</p><pre>def check_values(df):<br>    data = []<br>    for col in df.columns:<br>        data.append([col, \<br>                     df[col].dtype, \<br>                     df[col].isna().sum(), \<br>                     round(100*(df[col].isna().sum()/len(df)),2), \<br>                     df[col].nunique()<br>                     ])<br>    return pd.DataFrame(columns=[&#39;dataFeatures&#39;, &#39;dataType&#39;, &#39;null&#39;, &#39;nullPct&#39;, &#39;unique&#39;],data=data)</pre><pre>check_values(df_hotels)</pre><p>The result of the function would be as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/1*Gvgu0ldyeYdHykvmNOrnmw.jpeg" /></figure><p>Here is the result table from the function above, from the data types, null values together with the percentages value, and total unique value. <em>(Note: this table only represents 21 from the total of 33 columns).</em></p><h3>Question 2</h3><blockquote>How many visitors canceled their bookings and were not canceled? Then, explain the summary of the phenomenon.</blockquote><p>In the hotel dataset, there is one column called is_canceled, which is explained in a Boolean type whether the visitors canceled their reservations (1) or not (0). Thus, to answer Question 2, the is_canceled column should apply value_counts() for counting the value based on the visitors with the syntax together with the results below.</p><pre>df_hotels.is_canceled.value_counts()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*60p8Wx7kyXzrjaRhIVIImA.jpeg" /></figure><p>So, from the results above, we could see that around 44,224 visitors have canceled their bookings. Onto the next step, we would like to find the percentage of cancelations from the previous value above by adding <em>normalize = True</em> inside the value_counts() function that would divide both values (either in 0 or 1 row) over the total hotel visitors.</p><pre>df_hotels.is_canceled.value_counts(normalize=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/269/1*Mf52LNINTDlZidbdmcMIQg.jpeg" /></figure><p>Hence, we obtained around 37% of cancelations by hotel visitors on their bookings. After knowing the cancelation percentages, then we want to visualize into column graphs using the seaborn library including the title and x-axis name in the syntax below:</p><pre>sns.countplot(data=df_hotels, x=&#39;is_canceled&#39;)<br>plt.title(&#39;Cancelled Reservations&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*XsAnVJLwNmiMx7-IfDJ5MA.jpeg" /><figcaption>Canceled reservations comparison</figcaption></figure><p>Basically, the seaborn library has the same function as Matplotlib library which have many kinds of graph plots, especially for the is_canceled column. However, seaborn is more effective because it uses less syntax and is more efficient.</p><h3>Question 3</h3><blockquote>Find out the values of:<br>A. Cancelation reservations for the “City Hotel”<br>B. Cancelation reservations for the“Resort Hotel”</blockquote><p>For answering number 3 part A, we took df_hotels with ‘<em>hotel’ </em>as the main parameter, because we would like to show the cancelation rate for the City Hotel. We could use len() function that similarly works with the value_counts() to count the total rows within condition is_canceled==1 for the City Hotel. Here are the syntax and the results for this case.</p><pre>len(df_hotels[(df_hotels.hotel==&#39;City Hotel&#39;)&amp;(df_hotels.is_canceled==1)]) / len(df_hotels[(df_hotels.hotel==&#39;City Hotel&#39;)])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/156/1*ZLb5_Jsy9IqnI35ESN9OYQ.jpeg" /><figcaption>Result of the cancelation rate of City Hotel reservations</figcaption></figure><p>From the syntax above, the cancelation rate of City Hotel reservations is around <strong>0.417 or 42%</strong>.</p><p>Similar to the number 3 part A, we took the <em>‘hotel’</em> data from df_hotels. Instead of picking the ‘City Hotel’, now we would like to change to ‘Resort Hotel’ inside the len() function to look at the cancelation rate for this hotel type, with the syntax and the results below:</p><pre>len(df_hotels[(df_hotels.hotel==&#39;Resort Hotel&#39;)&amp;(df_hotels.is_canceled==1)]) / len(df_hotels[(df_hotels.hotel==&#39;Resort Hotel&#39;)])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/158/1*L-qOcL3l_PwixQ-H9DVgFA.jpeg" /><figcaption>Result of the cancelation rate of Resort Hotel reservations</figcaption></figure><p>From the syntax above, the cancelation rate of Resort Hotel reservations is around <strong>0.278 or 28%</strong>.</p><h3>Question 4</h3><blockquote>Filter the dataframe to only show the reserved (and not canceled) visitors, and save it in a variable.</blockquote><p>For this question, we should take the df_checkout as the main variable with the conditioned df_hotels as follows in a syntax:</p><pre>df_checkout = df_hotels[df_hotels.is_canceled == 0]<br>df_checkout.shape</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/98/1*au5CgYRIYQISh38JudpAYw.jpeg" /><figcaption>Variables of checkout value count</figcaption></figure><p>As seen above, df_checkout.shape was used to identify the value counts of the checkout reservations. Thus, there are 75,166 visitors who checked out their reservations from the total of 119,390 visitors.</p><h3>Question 5</h3><blockquote>A. Show the reservation summary per month for each hotel type<br>B. Indicate which month had the most reservations for each type and create a <strong>brief conclusion</strong> for both trends in each hotel.<br>C. Do a similar process as B, with the month name had been mapped into numbers.</blockquote><p>Now we are going to solve question part A and B to show the reservation summary per month for each hotel type and indicate the most reservations for each hotel type. For part A, the <em>‘hotel’</em> and <em>‘arrival_date_month’ </em>values should be categorized in the groupby() function which has a similar use as SQL as well. Here is the syntax for showing those values below:</p><pre>df_checkout.groupby([&#39;hotel&#39;,&#39;arrival_date_month&#39;])[&#39;id&#39;].nunique()</pre><p>From the syntax above, [‘id’].nunique() was added in the syntax for identifying the unique value of the IDs, and we could obtain the results below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/329/1*0bzSDvCw_0ZiW_2XeZoNVg.jpeg" /><figcaption>Reservations by each month</figcaption></figure><p>From the results above, we could directly answer part B for the most reservations for each hotel type. Hence, the most reserved month for either City Hotel or Resort Hotel <strong>occurred in August.</strong></p><p>Onto part C, for creating the mapping on each month, the calendar dictionaries should be imported and extracted the numbers of the month by using enumerate() function in the syntax below:</p><pre>import calendar<br><br>month_dict = {month: index for index, month in enumerate(calendar.month_name) if month}<br>month_dict</pre><p>Below are the results after calendar library extraction:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/155/1*dNf3ENrjIzrAgVi91_pqlg.jpeg" /></figure><p>Right after we got the extraction results, each column of arrival_date_month_num would be mapped into the suitable numbers and grouped by the syntax followed by the results below:</p><pre>df_checkout[&#39;arrival_date_month_num&#39;] = df_checkout[&#39;arrival_date_month&#39;].map(month_dict)<br>df_checkout.groupby([&#39;hotel&#39;,&#39;arrival_date_month_num&#39;]).size()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/355/1*fz3mD2td4jsHi52cWALqbg.jpeg" /><figcaption>Reservations based on each month after numerical mapping</figcaption></figure><p>Then, the next step after numerical mapping was the graphical plotting in seaborn syntax using the countplot() function with <em>‘df_checkout’</em> and <em>‘arrival_date_month_num’</em> for the dimensional axis of the graph. Besides, each axis was labeled ‘Arrival Month’ for the x-axis and ‘Total Reservation’ for the y-axis, as represented by the syntax below:</p><pre>sns.countplot(data=df_checkout, x=&#39;arrival_date_month_num&#39;,hue=&#39;hotel&#39;)<br>plt.xlabel(&#39;Arrival Month&#39;)<br>plt.ylabel(&#39;Total Reservations&#39;)<br>plt.show()</pre><p>And here is the graphical plotting result from the syntax above:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*f8pBQVJSjuk9W3V1A1DwOA.jpeg" /><figcaption>Visualization of hotel reservations</figcaption></figure><p>With the graphical support, information could be delivered and more understandable.</p><h3>Question 6</h3><blockquote>A. Create a new column called ‘arrival_date’ in a complete form (date, month, year)<br>B. Change the data type of the column into <strong>datetime </strong>(Tips: Combine date, month, and year into yyyy-mm-dd format)</blockquote><p>In this question, we should change the data type of the <em>‘arrival_date_month_num’</em> into a string datatype by using the syntax below:</p><pre>df_checkout.arrival_date_month_num.astype(&#39;str&#39;)</pre><p>Next, we should add zero padding to build a double-digit date variable, so for example 5 into 05 thanks to the padding. (Note: this syntax should be in chained with the previous step)</p><pre>df_checkout.arrival_date_month_num.astype(&#39;str&#39;).str.pad(2,fillchar=&#39;0&#39;)</pre><p>Then, after chaining two previous steps, we could implement the combination of date, month, and year using the syntax below:</p><pre>df_checkout[&#39;arrival_date&#39;] = \<br>    df_checkout[&#39;arrival_date_year&#39;].astype(&#39;str&#39;) + &#39;-&#39; +\<br>    df_checkout.arrival_date_month_num.astype(&#39;str&#39;).str.pad(2,fillchar=&#39;0&#39;) + &#39;-&#39; +\<br>    df_checkout.arrival_date_day_of_month.astype(&#39;str&#39;).str.pad(2,fillchar=&#39;0&#39;)<br><br>df_checkout[&#39;arrival_date&#39;]</pre><p>And here is the result below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*esi614LrT6iI47h8CfebsA.jpeg" /></figure><p>As seen in the result above, the datatype was still in an object format. Therefore, as question B had requested, we should change the datatype by using the pandas library in the syntax below:</p><pre>df_checkout[&#39;arrival_date&#39;] = pd.to_datetime(df_checkout.arrival_date)<br>df_checkout[&#39;arrival_date&#39;]</pre><p>The pd.to_datetime() would change the datatype into datetime, and would result on the image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*r36sH-ag5V4VK9YJe7bxzA.jpeg" /></figure><p>Now, we see the changes of the datatype from object into datetime64.</p><h3>Question 7</h3><blockquote>Build 2 (two) dataframes using the arrival_date column to display:<br>A. Total daily reservations (df_reservasi_perhari)<br>B. Weekly average reservations (avg_df_reservasi_perhari)<br>, and tell the difference between data A and B.</blockquote><p>In this question, we want to develop two dataframes from the total daily reservations (df_reservasi_perhari) and average weekly reservations (avg_df_reservasi_perhari) by extracting the df_checkout table to examine the arrival_date column contained inside the corresponding table for making a new table as follows:</p><pre>df_reservasi_perhari = df_checkout.resample(&#39;D&#39;,on=&#39;arrival_date&#39;).size().reset_index().rename(columns={0:&#39;total_reservasi&#39;})<br>df_reservasi_perhari</pre><pre>df_avg_reservasi_harian = df_checkout.resample(&#39;D&#39;,on=&#39;arrival_date&#39;).size().reset_index().rename(columns={0:&#39;total_reservasi&#39;}).\<br>resample(&#39;W&#39;,on=&#39;arrival_date&#39;)[&#39;total_reservasi&#39;].mean().reset_index()<br>df_avg_reservasi_harian</pre><p>As you could look in the syntax, there is resample() function that summarizes data by a time period, in which we use D (day) on the function, while on the second syntax, the second resample() function use W (week) to calculate the mean() function for the average reservations in a weekly timeline. Then, there are also reset_index(), size(), and rename() functions [for renaming a column from 0 to a certain name]. The results from those syntaxes are as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/289/1*RrqpGZRylAHSXdffSWTPWg.jpeg" /></figure><p>The result above is for the total daily reservations, while the result for the weekly average reservations would be shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/278/1*MPAIUdkZhnoid5he33BpXA.jpeg" /></figure><p>Moreover, for creating the plotting graph for the total daily reservations based on the time period, the syntax would be as shown below:</p><pre>plt.figure(figsize=(10,4))<br>sns.lineplot(data=df_reservasi_perhari, x=&#39;arrival_date&#39;, y=&#39;total_reservasi&#39;)<br>plt.title(&#39;Reservasi Harian&#39;, fontsize=&#39;x-large&#39;)<br>plt.show()</pre><p>And the result for the syntax above is displayed below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*lGI1CzH8xQGwy8iD69h03g.jpeg" /></figure><p>From the chart above, it was really difficult to analyze and obtain information related to the chart. Instead of developing a graph for each day, we developed a chart based on the weekly average reservations, which the graph plot would be represented in the following syntax below:</p><pre>plt.figure(figsize=(10,4))<br>sns.lineplot(data=df_avg_reservasi_harian, x=&#39;arrival_date&#39;, y=&#39;total_reservasi&#39;)<br>plt.title(&#39;Rata-Rata Reservasi Harian&#39;, fontsize=&#39;x-large&#39;)<br>plt.show()</pre><p>And the result for the syntax above is displayed below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*vDIyol5TVHnsWI8tWpu57Q.jpeg" /></figure><p>Thus, from the latest chart, we could obtain useful information and easier to gain insights related to the reservations for those hotels.</p><h3>Question 8</h3><blockquote>A. Find the average of ADR based on the hotel type and customer types<br>B. What customer type had the biggest ADR on each hotel type?</blockquote><p>For case A, it is pretty simple because the only thing required for solving this problem is to cluster the ADRs based on the hotel type and customer types, represented in the syntax below:</p><pre>df_checkout.groupby([&#39;hotel&#39;,&#39;customer_type&#39;])[&#39;adr&#39;].mean()</pre><p>Thus, the result would be as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*Q4mMMjC1UDve_M6GVkkbjA.jpeg" /></figure><p>From those hotel types, the highest average of the ADR is held by the Transient customer group for the City Hotel, while the lowest average of ADR is held by the Transient-Party customer group for the Resort Hotel.</p><p>Then, for obtaining the customer type with the biggest ADR, we could answer it by a boxplot in the syntax below:</p><pre>plt.figure(figsize=(8,6))<br>sns.boxplot(data=df_checkout, x=&#39;adr&#39;, y=&#39;hotel&#39;,hue=&#39;customer_type&#39;)<br>plt.show()</pre><p>The syntax result is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*HRgs_IG3Hw_p3rQ_a9wqMg.jpeg" /></figure><p>From the boxplot above, we could state that the Transient customer group had the greatest value of ADRs.</p><h3>Question 9</h3><blockquote>By using the ‘df_country’ dataframe which consist of the country and its code information, show the <strong>top 10 </strong>countries with the biggest booking orders!</blockquote><p>For answering this problem, first, we should import the country dataset as follows (with the results right after):</p><pre>df_country = pd.read_csv(&#39;https://gist.githubusercontent.com/tadast/8827699/raw/f5cac3d42d16b78348610fc4ec301e9234f82821/countries_codes_and_coordinates.csv&#39;)<br>df_country.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*xSBTfmIKad9rAlHlBGqBDA.jpeg" /></figure><p>Then, there are two questions related to the dataset:<br>A. Could we use the Alpha-3 code as the join key to the hotel dataset?<br>B. Are all the countries&#39; codes included inside the dataset?</p><p>Since the Alpha-3 code was likely to be joined into the hotel dataset and contain 3 letters for each country with the double quote that wants to be removed, we should delete those quotes by the following syntax below:</p><pre>df_country[&#39;code&#39;] = df_country[&#39;Alpha-3 code&#39;].str.replace(&#39;&quot;&#39;,&#39;&#39;).str.strip()</pre><p>After creating a new column for the new country code, we could merge the dataset with the Panda library below:</p><pre>df_merged = pd.merge(df_checkout[[&#39;id&#39;,&#39;country&#39;]],<br>                     df_country[[&#39;Country&#39;,&#39;code&#39;]],<br>                     left_on=&#39;country&#39;,<br>                     right_on=&#39;code&#39;,<br>                     indicator=True,<br>                     how=&#39;left&#39;)<br>df_merged.head()</pre><p>As a result, the result from the merged datasets would be shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*aoFxRMTmvQESKOIuKk3EyQ.jpeg" /></figure><p>And, to check how many values that could be joined, we could use the syntax with the result below:</p><pre>df_merged._merge.value_counts()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/208/1*JKG8UwAPZdIrjbPf1oeh4Q.jpeg" /></figure><p>From this result, 74,269 data appeared on both tables, while only 1,448 data appeared on the country table, and nothing to joined on the checkout table. Afterward, we want to extract the top 10 countries with the highest bookings by the syntax while still using the merged functions and the results below:</p><pre>df_merged.Country.value_counts().head(10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/219/1*jUsytiGXzLHa-985sHWdKA.jpeg" /></figure><p>From the results above, Portugal is the country with the most bookings, followed by the United Kingdom, and France, going down until the United States in the tenth position. Then, to visualize the top 10 highest booking countries, we could use the bar plot by the syntax below:</p><pre>df_merged.Country.value_counts().head(10).sort_values(ascending=True).plot.barh()<br>plt.show()</pre><p>Thus, the plot result of the top 10 most booking countries would be as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/1*2QIb7j03TuWC9UWglVLVig.jpeg" /></figure><h3>Question 10</h3><blockquote>A. How many guests were stayed for each reservation?<br>B. Which guest contains the maximum number of guests based on the dataset? (Including the data that fulfilled the maximum value of total guests)</blockquote><p>To determine the total number of guests who stayed in their own reservations, we need to add all guests from all age categories, from adults, and children until babies as well by the syntax below:</p><pre>df_checkout[&#39;total_guest&#39;] = df_checkout.adults + df_checkout.children + df_checkout.babies<br>df_checkout.total_guest.describe()</pre><p>As you could see in the related syntax, there is a function called describe(), which would display all statistical values from the summary, average, maximum, minimum, median, and quartile values of guests. Then, right after creating the syntax above, the results would be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/276/1*wxNBlTd6ZBh4gNbBTVQOmw.jpeg" /></figure><p>Those are all statistical data from the guests, with a <strong>maximum number of guests of 12 (twelve), and 7,516 guests were reserved and stayed at their booked hotel.</strong></p><p>Moreover, we would like to identify which guest ID brought the maximum number of guests. Thus, we should call the function based on the maximum value by the syntax below:</p><pre>df_checkout[df_checkout.total_guest==df_checkout.total_guest.max()].T</pre><p>Hence, the guest ID could be identified as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/399/1*ZHBuFgONW_KtHxyWFEWGuw.jpeg" /></figure><p>So, <strong>Guest ID number 46619</strong> brought the maximum values of guests based on the data analysis and calculation from the previous syntax.</p><p>That wraps all the answers related to the hotel business and provides solutions through Python. Hopefully, you gaining more insights into Python to solve any business case. Thank you for the time to read this article, and see you later. Doei!</p><h3><strong>Bibliography</strong></h3><ol><li><a href="https://www.simplilearn.com/top-python-libraries-for-data-science-article">https://www.simplilearn.com/top-python-libraries-for-data-science-article</a></li><li><a href="https://glints.com/id/lowongan/google-colab-adalah/#.ZBGLu3ZBzIV">https://glints.com/id/lowongan/google-colab-adalah/#.ZBGLu3ZBzIV</a></li><li><a href="https://blog.devgenius.io/myskill-data-analysis-part-2-python-for-data-visualization-a2c514a3a9c7">https://blog.devgenius.io/myskill-data-analysis-part-2-python-for-data-visualization-a2c514a3a9c7</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd1b6e35aeef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL in the Data Analysis world [Pakistani E-Commerce]]]></title>
            <link>https://medium.com/@mikerhrdja/sql-in-the-data-analysis-world-2df629c7cc2?source=rss-d0dcf90dce5c------2</link>
            <guid isPermaLink="false">https://medium.com/p/2df629c7cc2</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[Michael Rahardja]]></dc:creator>
            <pubDate>Wed, 15 Mar 2023 10:47:50 GMT</pubDate>
            <atom:updated>2025-02-10T22:48:22.886Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rE_7kirnouJ_6NKH" /><figcaption>Photo by <a href="https://unsplash.com/@kmuza?utm_source=medium&amp;utm_medium=referral">Carlos Muza</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Hi, all Medium readers! This is my first article on Medium and would mark my journey in many journals on this platform, especially in Data Analysis, Data Science, and more. Therefore, to start my post, I would like to explain the details of Data Analysis processes using SQL (Structured Query Language). This article will be part of the requirements from MySkill to obtain a <em>Master Participant</em> certificate level in the Data Analysis Bootcamp. Before I finally joined this Bootcamp, I already had the SQL basics. However, by participating in this Bootcamp, I would gain more insights and knowledge about SQL in the real world from the experienced mentors and supportive colleagues.</p><p>So, what is SQL? Based on <a href="https://www.w3schools.com/sql/#:~:text=SQL%20is%20a%20standard%20language,Start%20learning%20SQL%20now%20%C2%BB">W3Schools</a>, SQL, or <em>Structured Query Language, </em>is a standard language for storing, manipulating, and retrieving data in databases. In addition, SQL is also able to create databases by importing data from many formats, such as .csv or .txt files. These discussions focus on the fundamental clauses and commands (SELECT…FROM, WHERE, ORDER BY, LIKE, LIMIT), aggregations (SUM, AVG, MAX, MIN, HAVING, GROUP BY), logical operations (AND, OR, NOT), subqueries (WITH), JOINS, and many more.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*c4duWsFgVAn5UPUM7ErAew.png" /><figcaption>SQL (Source: Flaticon)</figcaption></figure><p>In the data analysis, the procedures are explained below:</p><p>1. Defining the major problem<br>2. Confirming the analysis points of the data<br>3. Find suitable data for the analysis<br>4. Data preprocessing (Remove duplicates and suppress data anomalies, dirty data handling, missing data management, and data standardization.)<br>5. Analyzing the data based on its needs<br>6. Interpret and visualize the data</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*wCu9Z_ae6SdsVFkUUjkxpw.jpeg" /><figcaption>Flowchart of Data Analysis</figcaption></figure><p>When talking about the analysis section (blue box), several viable options could be utilized based on the environment, which is:<br>- Query-based: PostgreSQL, MySQL, BigQuery<br>- Spreadsheet-based: Microsoft Excel, Google Sheets<br>- Coding-based: Python, R</p><p>From the processes above, SQL is mainly used in data analysis for most cases that would like to be solved later, especially in the business sector.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*lEicAnoqihVfywpefCF29w.jpeg" /><figcaption>Example of Data Analysis Tools (images source from Google)</figcaption></figure><p>In this article, we will solve business cases and problems using PostgreSQL as the primary analysis tool. In particular, we are purposed to find solutions for an e-commerce business from Pakistan. The datasets that would be used for this article originated from Kaggle named <a href="https://www.kaggle.com/datasets/zusmani/pakistans-largest-ecommerce-dataset">Pakistan’s Largest E-Commerce Dataset</a>. The first thing before starting the analysis is to import the required datasets into PostgreSQL. There are 4 (four) datasets provided for this business case:</p><p>a. order_detail<br>b. sku_detail<br>c. customer_detail<br>d. payment_detail</p><p>All the datasets above were developed from the respective Bootcamp. Thus, importing the datasets within the queries is the only task. Before answering the questions, it is necessary to recognize some parameters from each dataset in columns.</p><p><strong>order_detail </strong>:<br>1. id: unique order number (id_order)<br>2. customer_id: unique customer number<br>3. order_date: transaction dates<br>4. sku_id: unique codes/ numbers for a product (SKU is the abbreviation of Stock Keeping Unit)<br>5. price: the tagged price for a product<br>6. qty_ordered: total amounts of the purchased product<br>7. before_discount: the total price of a product (price * qty_ordered)<br>8. discount_amount: applied discount values of total products<br>9. after_discount: the total price of a product after discount reduction<br>10. is_gross: indicates the customer who has yet to pay<br>11. is_valid: indicates the customer who had fulfilled their payment<br>12. is_net: indicates the customer whose transaction is done<br>13. payment_id: unique code for payment method</p><p><strong>sku_detail</strong> :<br>1. id: unique codes/ numbers for a product<br>2. sku_name: product name<br>3. base_price: the tagged price for a product<br>4. cogs: cost of goods sold<br>5. category: product category</p><p><strong>customer_detail</strong> :<br>1. id: unique customer number<br>2. registered_date: dates of the first customer’s registration</p><p><strong>payment_detail</strong> :<br>1. id: unique code for payment method<br>2. payment_method: method of payment that is used</p><p>After all of the parameters had been defined by each dataset, the analysis process could be initiated.</p><p>Now, 10 (ten) provided questions would like to be solved to provide solutions for this business case. All of the answers would be filtered <strong><em>using is_valid = 1 for the data transactions filtering</em></strong>, which means all solutions would be filtered only for the customer who had fulfilled their payment for all questions below.</p><h3>Case 1</h3><blockquote><strong>Alongside 2021, which month had the most transaction values <em>(after_discount)</em>?</strong></blockquote><p>To answer every business question, it is necessary to find out which column you would like to use. Thus, in this first case, there are 2 (two) main columns required to solve number 1, which are:<br>1. <em>Month</em>, to cluster the data transactions<br>2. <em>Total sales</em>, clusterized by the <em>Month</em> column<br><br>Those required data or parameters did not available from all the initial datasets. However, those parameters could be obtained through data manipulation. ‘<em>Month’</em> data was obtained by filtering the order_date column and converted into text datatype when total sales could be generated by adding all sales by each month from the after_discount column, in which both columns are provided in the <strong>order_detail</strong> dataset table.</p><pre>--N1--<br>SELECT TO_CHAR(order_date, &#39;Month&#39;),<br>SUM(after_discount) AS total_aftdisc FROM order_detail<br>WHERE is_valid = 1 AND order_date BETWEEN &#39;2021-01-01&#39; AND &#39;2021-12-31&#39;<br>GROUP BY TO_CHAR(order_date, &#39;Month&#39;)<br>ORDER BY total_aftdisc DESC;</pre><p>Within the <strong>is_valid = 1</strong> filter, order dates were limited to 1st January 2021 and 31st December 2021. Then, the summary aggregation was applied to the after_discount column and combined with GROUP BY clauses for the filtered order_date column to add all sales based on their month. Lastly, the ORDER BY clause applied from the total_aftdisc column from the highest to the lowest value by adding DESC by the end of the query.</p><p>And here is the obtained result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/273/1*_3h0b0_XllQVnXy2bydMIQ.jpeg" /><figcaption>Total sales by each month.</figcaption></figure><p>From the table above, <strong>November (Month no.11)</strong> can be known as the most total sales for the 2021 period.</p><h3>Case 2</h3><blockquote><strong>Throughout all transactions in 2021, which month had the most total customers (unique), total orders (unique), and product quantity amounts?</strong></blockquote><p>For this question, there are 4 (four) main columns required to solve number 1, which are:<br>1. <em>Month</em>, to cluster the data transactions<br>2. <em>Total customers</em>, clusterized by the <em>Month</em> column<br>3. <em>Total orders</em>, clusterized by the <em>Month</em> column<br>4. <em>Total quantity</em>, clusterized by the <em>Month</em> column</p><p>Similar to the number 1 process, “Month” data was obtained by filtering the order_date column and converting it into text datatype. Besides, the total number of customers and total orders were counted based on the total data on the dataset filtered using the DISTINCT clause to reduce data duplication and counted as a unique value. Then, the total order quantities could be generated by adding all sales by each month from the qty_ordered column in the <strong>order_detail</strong> dataset table.</p><pre>--N2--<br>SELECT TO_CHAR(order_date, &#39;Month&#39;) AS month, <br>COUNT(DISTINCT order_detail.customer_id) AS total_customer, <br>COUNT(DISTINCT order_detail.id) AS total_order,<br>SUM(qty_ordered) AS total_quantity FROM order_detail<br>WHERE is_valid = 1 AND order_date BETWEEN &#39;2021-01-01&#39; AND &#39;2021-12-31&#39;<br>GROUP BY TO_CHAR(order_date, &#39;Month&#39;)<br>ORDER BY total_customer DESC;</pre><p>From the explanation above, order dates were limited to 1st January 2021 and 31st December 2021. Later, COUNT and SUM aggregations were applied and bundled inside GROUP BY clause for the month column, before ORDER BY was applied by the total_customer column and added DESC to show it from the biggest value.<br><br>And here is the result of the queries above:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*HiVhbWkiszXIXcF-0NMQ9A.jpeg" /><figcaption>Total quantities, orders, and customers from each month (Largest to smallest)</figcaption></figure><p>As shown in the table above, the highest orders, quantities, and customers were located in<strong> month no. 11 or November.</strong></p><h3>Case 3</h3><blockquote><strong>During 2022, which category generates the biggest transaction values?</strong></blockquote><p>To solve this problem, there are required data that had to be fulfilled:<br>1. Product category (obtained from sku_detail dataset)<br>2. Total transaction values (obtained from order_detail dataset)<br><br>Because there are two different datasets required to be called, therefore those datasets should be combined by using the JOIN clause. Before heading to more details, there are several types of joins in SQL. However, to eliminate any (null) values, INNER JOIN was selected, because it is simply selecting records that have matching values in both tables.</p><pre>--N3--<br>SELECT sku_detail.category, SUM(order_detail.after_discount) AS total_trsc FROM order_detail<br>INNER JOIN sku_detail<br>ON order_detail.sku_id = sku_detail.id<br>WHERE is_valid = 1 AND order_date BETWEEN &#39;2022-01-01&#39; AND &#39;2022-12-31&#39; <br>GROUP BY sku_detail.category<br>ORDER BY 2 DESC;</pre><p>The main focus of this question is to filter the total sales by its category. Thus, the sku_detail.category was selected together with the total_trsc column (using SUM aggregations on the after_discount column). The GROUP BY function should be combined with the SUM aggregation for each category and the ORDER BY (column_selection) DESC clause to show the biggest value on the top table. As seen above, the ORDER BY was called no 2. It means that the table would be ordered by the second column of the queries, which is the total_trsc values. The results would be as shown in the table below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/1*ApvOmrkUev6MyBxDHW2WsA.jpeg" /><figcaption>Total transaction values from each category</figcaption></figure><p>From the table above, <strong>the Mobiles &amp; Tablets category generates the biggest transaction values</strong>, while the Books category generates the lowest transaction values.</p><h3>Case 4</h3><blockquote><strong>Compare the transaction values between 2021 and 2022 by each product category. Describe which category had raised and which category had plunged in transaction values.</strong></blockquote><p>In this case, there 4 (four) required parameters to be included:<br>1. Product category<br>2. Total sales in 2021<br>3. Total sales in 2022<br>4. Total sales differences between 2021 and 2022<br><br>The main goals of this question are to give insights into each category based on their transaction values in 2021–2022 and state the growth of those categories. Because those highlighted parameters require several columns from two datasets, then INNER JOIN was applied between order_detail and sku_detail for the unique product number as the main key for the joins.</p><pre>--N4--<br>SELECT sku_detail.category,<br>SUM(CASE WHEN (to_char(order_date, &#39;yyyy-mm-dd&#39;) BETWEEN &#39;2021-01-01&#39; AND &#39;2021-12-31&#39;) THEN order_detail.after_discount END) AS totalsales21,<br>SUM(CASE WHEN (to_char(order_date, &#39;yyyy-mm-dd&#39;) BETWEEN &#39;2022-01-01&#39; AND &#39;2022-12-31&#39;) THEN order_detail.after_discount END) AS totalsales22,<br>((SUM(CASE WHEN (to_char(order_date, &#39;yyyy-mm-dd&#39;) BETWEEN &#39;2022-01-01&#39; AND &#39;2022-12-31&#39;) THEN order_detail.after_discount END) / <br>  SUM(CASE WHEN (to_char(order_date, &#39;yyyy-mm-dd&#39;) BETWEEN &#39;2021-01-01&#39; AND &#39;2021-12-31&#39;) THEN order_detail.after_discount END)) - 1) AS grow_points<br><br>FROM order_detail<br>INNER JOIN sku_detail<br>ON order_detail.sku_id = sku_detail.id<br>WHERE is_valid = 1 AND order_date BETWEEN &#39;2021-01-01&#39; AND &#39;2022-12-31&#39; <br>GROUP BY 1<br>ORDER BY 4 DESC;</pre><p>So, the sku_detail.category is selected as the main column for the manipulation, with the order_date column from the order_detail dataset. One interesting thing about the queries above is the CASE WHEN (column_selection) THEN (results) END function for the order dates. As shown above, the function was applied for both totalsales21 and totalsales22 inside the date range of each year, while the after_discount column was considered as the result of the total sales within the function. Here in the queries, sku_id is selected as the joined column between two datasets by a limited range from 1st January 2021 to 31st December 2022. The GROUP BY function combined with the SUM aggregation for the total sales and the ORDER BY (column_selection) DESC clause to be arranged based on the grow_points column.</p><p>Here is the result of the queries in the table below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*oNGBJf5NYZijDsOTwoXvgQ.jpeg" /><figcaption>Growth points and total sales of each category</figcaption></figure><p>As a result, there are four categories on the bottom table of sales growth:</p><p>1. Men’s Fashion<br>2. Soghaat<br>3. Books<br>4. Others,</p><p>while four categories had the biggest sales growth. Those were occupied by:</p><p>1. Women’s Fashion<br>2. Superstore<br>3. Kids &amp; Baby<br>4. Entertainment</p><h3>Case 5</h3><blockquote><strong>Show the top 10 product names together with their categories based on the transaction values throughout 2022, including the total customers (unique), total orders (unique), and total product quantities.</strong></blockquote><p>For this question, six parameters are required for solving the problem.<br>1. Product name <br>2. Product category<br>3. Total sales<br>4. Total unique customers<br>5. Total unique orders<br>6. Total quantity</p><p><em>(Notes: Parameters (1) and (2) were obtained from the sku_detail dataset, while others could be obtained by taking the initial record from the order_detail dataset.)</em></p><p>The main purpose of collecting those parameters was to determine the top 10 product names with their categories based on the total sales in 2022, and three of them were going to be the main compositions of the solution, with parameters (1) and (2) for categorizing and parameter no (3) for value arrangements. Since two datasets were used, then the INNER JOIN function was applied to the unique product ids.</p><pre>--N5--<br>SELECT sku_detail.sku_name, sku_detail.category, <br>SUM(order_detail.after_discount) AS total_aftdisc, <br>COUNT(DISTINCT order_detail.customer_id) AS total_customers, <br>COUNT(DISTINCT order_detail.id) AS total_order, <br>SUM(order_detail.qty_ordered) AS total_qty<br>FROM order_detail<br>INNER JOIN sku_detail<br>ON order_detail.sku_id = sku_detail.id<br>WHERE is_valid = 1 AND order_date BETWEEN &#39;2022-01-01&#39; AND &#39;2022-12-31&#39; <br>GROUP BY 1,2 <br>ORDER BY 3 DESC<br>LIMIT 10;</pre><p>Inside the data manipulation processes from parameters (3) to (6), SUM aggregations are applied for total sales <em>(total_aftdisc)</em> and total quantities <em>(total_qty) </em>to add all of the sales and quantity values when COUNT and DISTINCT functions are applied for total customers and orders to count the distinctive customers and orders. Later on, the applied aggregation functions on parameters (3) and (4) were joined inside the GROUP BY function with the product name and product category, with an ORDER BY clause on total sales from the largest using DESC and restricted into 10 records by LIMIT 10.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*U6NxZtxEp_k7gfCB8s6gWA.jpeg" /><figcaption>Finding the largest total sales from the product names and categories</figcaption></figure><p>The table above shows the top 10 product names, including their categories, total sales, and other companion parameters, with <strong>IDROID_BALRX7-Gold having the largest total sales in the Mobiles &amp; Tablets category</strong>.</p><h3>Case 6</h3><blockquote><strong>Display the top 5 most popular payment methods for 2022 based on the total unique orders.</strong></blockquote><p>Now, in this case, only 2 (two) record columns are necessary for solving the question:<br>1. Payment method (obtained from payment_detail dataset)<br>2. Total unique order (obtained from order_detail dataset)<br><br>To solve the question, only one function was important to be done, which is the INNER JOIN function on the payment_id key, because the payment method could be determined by finding their payment ids within 2022 from the order_date key.</p><pre>--N6--<br>SELECT payment_detail.payment_method, <br>COUNT(DISTINCT(order_detail.id)) AS total_order FROM order_detail<br>INNER JOIN payment_detail<br>ON order_detail.payment_id = payment_detail.id<br>WHERE is_valid = 1 AND order_date BETWEEN &#39;2022-01-01&#39; AND &#39;2022-12-31&#39;<br>GROUP BY 1<br>ORDER BY 2 DESC<br>LIMIT 5;</pre><p>In this query, order ids were distinctively counted by COUNT and DISTINCT clauses, before being categorized by the payment method and ordered by the total_order column. The result is shown in the table below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/266/1*i1Ns9Ipn-0Zu7Wzs5kL2iQ.jpeg" /><figcaption>Top 5 payment methods of the Pakistan e-commerce</figcaption></figure><p>Hence, the top 5 payment methods for that e-commerce are <strong>cod, Payaxis, Easypay, customer credit, and jazz wallet</strong>.</p><h3>Case 7</h3><blockquote><strong>Arrange these 5 (five) products based on the transaction values.</strong></blockquote><p>a. Samsung<br>b. Apple<br>c. Sony<br>d. Huawei<br>e. Lenovo</p><p>For this question, 5 (five) brand products were likely to be arranged based on the transaction values. Although the product name includes the brand inside each record, it is complex to be directly taken through their product names. Hence, data manipulation was required by creating a <em>pseudo table</em> (dummy table) for the sku_name keys from the brands listed above. As shown in the queries below, WITH clauses are applied for the <em>pseudo table </em>creations to extract the brand from the product name.</p><pre>--N7---<br>WITH X AS(<br>SELECT <br>(CASE <br> WHEN lower(sku_detail.sku_name) ILIKE &#39;%Samsung%&#39; THEN &#39;Samsung&#39;<br> WHEN lower(sku_detail.sku_name) ILIKE &#39;%Sony%&#39; THEN &#39;Sony&#39;<br> WHEN lower(sku_detail.sku_name) ILIKE &#39;%Lenovo%&#39; THEN &#39;Lenovo&#39;<br> WHEN lower(sku_detail.sku_name) ILIKE &#39;%Huawei%&#39; THEN &#39;Huawei&#39;<br> WHEN lower(sku_detail.sku_name) ILIKE &#39;%Apple%&#39;  OR lower(sku_detail.sku_name) ILIKE &#39;%iphone%&#39; <br> THEN &#39;Apple&#39; END) AS brand,<br>SUM(order_detail.after_discount) AS total_sales<br>FROM order_detail<br>INNER JOIN sku_detail on sku_detail.id = order_detail.sku_id<br>WHERE is_valid = 1 AND to_char(order_date, &#39;yyyy-mm-dd&#39;) BETWEEN &#39;2022-01-01&#39; AND &#39;2022-12-31&#39;<br>GROUP BY 1)<br><br>SELECT * FROM X<br>WHERE brand IS NOT NULL<br>ORDER BY 2 DESC<br>LIMIT 5;</pre><p>WITH clauses creation of table X is popular to be called Common Table Expressions (CTE), <a href="https://chartio.com/resources/tutorials/using-common-table-expressions/">a temporary named result set of query that is created and used only within the context of a large query</a>. WITH clause purposed to simply the complex queries for data manipulation purposes. Inside X, the CASE WHEN...THEN clause is selected from the sku_name key together with the lower() function to lower the letters. Afterward, ILIKE ‘%brands%’ function is applied to look at the particular brand from the product name. The ILIKE function is similar to the LIKE functions in SQL. The only difference is that the ILIKE function would neglect the sensitiveness of the characters from a record, which means that users could call a word, for example, a brand, whatever the character form inside the string (Example: ILIKE ‘&amp;SAmsunG%’ or ILIKE ‘%hUaWei%’). Then, the SUM function was applied to the after_discount key value, and the INNER JOIN function between the SKU ID’s from the order_detail and sku_detail datasets. At the end of X, the brand column should be categorized in the GROUP BY clause.</p><p>For the next step, table X should be called out to the main query by selecting all data keys from X, with brand filtering = NOT NULL, and arranged by the total sales from the largest on those 5 limited values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/1*LmGoet7CixA36Y-OulE28g.jpeg" /><figcaption>Top 5 total sales from the brands</figcaption></figure><p>As a result, the top 5 total sales brands are <strong>Samsung, Apple, Huawei, Lenovo, and Sony</strong>.</p><h3>Case 8</h3><blockquote><strong>Similar to no 3, show the profit comparison between 2021 and 2022 for each category, then show the differences from 2021 until 2022.</strong> (Note &gt;&gt; profit = after_discount — (cogs*qty_ordered))</blockquote><p>In the case of this number, there are several parameters to be fulfilled for data manipulations and subqueries:<br>1. Product category<br>2. Profits in 2021 and 2022 from the initial formula above within the required parameters<br>3. Profit growth points</p><p>In this case, each category was calculated based on the generated profit from 2021 to 2022 including the growth points of the profit. Because of the complexity of handling each category with their SKUs and the price inside the year range (2021 or 2022), a dummy table should be created to simplify all required information.</p><pre>--N8--<br>WITH Y AS(<br>SELECT sku_detail.category, to_char(order_date, &#39;YYYY-MM-DD&#39;) AS orders,<br>SUM(order_detail.after_discount - (sku_detail.cogs*order_detail.qty_ordered)) AS profit<br>FROM order_detail<br>INNER JOIN sku_detail ON sku_detail.id = order_detail.sku_id<br>WHERE is_valid = 1 AND to_char(order_date, &#39;YYYY-MM-DD&#39;) BETWEEN &#39;2021-01-01&#39; AND &#39;2022-12-31&#39;<br>GROUP BY 1,2<br>ORDER BY 3 DESC<br>),<br><br>Z AS(<br>SELECT Y.category, <br>SUM(CASE WHEN Y.orders BETWEEN &#39;2021-01-01&#39; AND &#39;2021-12-31&#39; THEN Y.profit END) AS profits_2021,<br>SUM(CASE WHEN Y.orders BETWEEN &#39;2022-01-01&#39; AND &#39;2022-12-31&#39; THEN Y.profit END) AS profits_2022<br>FROM Y<br>GROUP BY 1<br>)<br><br>SELECT *,<br>(Z.profits_2022-Z.profits_2021)/Z.profits_2021 AS growth_points<br>FROM Z<br>ORDER BY 4 DESC;</pre><p>For the case from this number, the process was quite similar to the previous case, in which WITH clause was used for CTE purposes. However, to obtain the profit growth points between 2021 and 2022, the CTEs were divided into 2 (two) steps represented in Tables Y and Z. For table Y, the dummy table was more focused on several points below:<br>a. Formulating the profits between 2021 and 2022 from the order_date by SUM aggregation<br>b. Utilizing the INNER JOIN function based on the SKU ids.<br>c. Categorizing with GROUP BY on the product category and orders key, including arrangements based on the profits.</p><p>Then, the Y table would be called in another dummy table named Z, in which all information from Table Y was set into Table Z. In addition, the SUM function was used for profit aggregations within CASE WHEN clauses for 2021 and 2022. Thereafter, the GROUP BY function called for clustering the product category.</p><p>Moreover, at the end of the analysis process, all keys from Table Z were selected with the formula of profit growth points and ordered from the highest value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*UZxBHgPQmIUj8e8bE0yfnQ.jpeg" /><figcaption>Profit growth points of each category</figcaption></figure><p>As a result of this case, there are four categories on the bottom table of profit growth:</p><p>1. Men’s Fashion<br>2. Others<br>3. Soghaat<br>4. Others,</p><p>while four categories had the biggest profit growth. Those were occupied by:</p><p>1. Women’s Fashion<br>2. Superstore<br>3. Computing<br>4. Entertainment</p><h3>Case 9</h3><blockquote><strong>Display the top 5 SKUs with the highest profit contributions in 2022 based on the Women’s Fashion category with the largest profit.</strong></blockquote><p>In this case, there are 3 (three) pieces of information required for manipulation:<br>1. Product ID<br>2. Product name<br>3. Profits on each product (based on the specific category &gt;&gt; Women’s Fashion)</p><p>For this case, each SKU was calculated based on the generated profit contribution in 2022 using the formula on number 8. To make it more effective, WITH clause was used for a <em>pseudo table</em>.</p><pre>--N9--<br>WITH D AS(<br>SELECT order_detail.id, sku_detail.sku_name, (order_detail.after_discount - (sku_detail.cogs * order_detail.qty_ordered)) <br> AS profit<br>FROM order_detail<br>INNER JOIN sku_detail ON sku_detail.id = order_detail.sku_id<br>WHERE is_valid =1<br>AND to_char(order_date, &#39;yyyy-mm-dd&#39;) BETWEEN &#39;2021-01-01&#39; AND &#39;2022-12-31&#39;<br>AND sku_detail.category = &#39;Women Fashion&#39;<br>)<br><br>SELECT D.sku_name,<br>SUM(D.profit) AS profit_sum<br>FROM D<br>GROUP BY 1<br>ORDER BY 2 DESC<br>LIMIT 5;</pre><p>Similar to 7 and 8, the dummy table D was created, in which inside the table there are several commands for data manipulation, starting from the INNER JOIN function on the IDs and category selection on Women’s Fashion.</p><p>The next one, outside the dummy table, the product name was called from table D since it was already joined, with the SUM function on profit_sum. Hereafter those commands, GROUP BY applied to the SKU name and ordered from the highest summary by the profit_sum…DESC and limited to only 5 (five) items.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/303/1*0-5wFGbDHZyKnUkc-FQDZw.jpeg" /><figcaption>Five product names with the biggest profit contributions in Women’s Fashion</figcaption></figure><p>Thus, those are the 5 (five) highest profit contributions from the Women’s Fashion category.</p><h3>Case 10</h3><blockquote><strong>Show the total unique order using the top 5 payment methods based on the product category during 2022.</strong></blockquote><p>In the last case, there are 2 (two) parameters needed to solve the case:<br>1. Product category<br>2. Payment methods<br><br>In this case, there are three datasets required to provide the solution to the question, which are sku_detail, order_detail, and payment_detail. Therefore, the INNER JOIN function should be done twice. The first joins would be on the product id key from sku_detail and order_detail and the second joins would be on the payment IDs between order_detail and payment_detail datasets.</p><pre>--N10--<br>SELECT sku_detail.category,<br>COUNT(DISTINCT CASE WHEN payment_detail.payment_method = &#39;cod&#39; THEN order_detail.id END) AS cod,<br>COUNT(DISTINCT CASE WHEN payment_detail.payment_method = &#39;Easypay&#39; THEN order_detail.id END) AS easypay,<br>COUNT(DISTINCT CASE WHEN payment_detail.payment_method = &#39;Payaxis&#39; THEN order_detail.id END) AS payaxis,<br>COUNT(DISTINCT CASE WHEN payment_detail.payment_method = &#39;customercredit&#39; THEN order_detail.id END) AS customercredit,<br>COUNT(DISTINCT CASE WHEN payment_detail.payment_method = &#39;jazzwallet&#39; THEN order_detail.id END) AS jazzwallet<br>FROM order_detail<br><br>INNER JOIN sku_detail ON sku_detail.id = order_detail.sku_id<br>INNER JOIN payment_detail ON payment_detail.id = order_detail.payment_id<br>WHERE is_valid = 1<br>AND TO_CHAR(order_date, &#39;yyyy-mm-dd&#39;) BETWEEN &#39;2022-01-01&#39; AND &#39;2022-12-31&#39;<br><br>GROUP BY sku_detail.category<br>ORDER BY cod DESC;</pre><p>To answer this question, within the joins inside the query, the product category was selected together with the payment method associated with the order IDs using COUNT, DISTINCT, and CASE WHEN...THEN functions for 5 (five) different payment methods. Following those functions, the product category was agglomerated inside GROUP BY functions and descendant sortation from 1 of the payment method. In this case, cod was selected for the arrangements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*d8I-9qWjCZcKjsVl8HP_AQ.jpeg" /><figcaption>Product categories with 5 different payment methods, sorted by the highest cod payment</figcaption></figure><p>Hence, the <strong>Men’s Fashion</strong> category<strong> holds the highest transactions on the cod method</strong>, when the highest payment from <strong>Easypay, PayAxis, and customer credits come from the Mobiles &amp; Tables category</strong>, and <strong>Superstore</strong> transactions are <strong>dominated by Jazz wallet payments</strong>.</p><p>Those are the 10 questions related to the e-commerce business case from Pakistan using SQL queries. Hopefully, this article would help you to solve many other business problems out there using queries. Thank you for your time in reading this article, and see you later.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2df629c7cc2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>