<?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 Kueila Ramos on Medium]]></title>
        <description><![CDATA[Stories by Kueila Ramos on Medium]]></description>
        <link>https://medium.com/@kueilaramos?source=rss-99cb0af6393e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*kQG-cILZPAkzQPUdnyyB-w.png</url>
            <title>Stories by Kueila Ramos on Medium</title>
            <link>https://medium.com/@kueilaramos?source=rss-99cb0af6393e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 01:31:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kueilaramos/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[Web Traffic Analysis with SQL]]></title>
            <link>https://kueilaramos.medium.com/web-traffic-analysis-with-sql-39e108cadfa2?source=rss-99cb0af6393e------2</link>
            <guid isPermaLink="false">https://medium.com/p/39e108cadfa2</guid>
            <category><![CDATA[mysql-workbench]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[marketing]]></category>
            <category><![CDATA[web-traffic]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Kueila Ramos]]></dc:creator>
            <pubDate>Mon, 10 May 2021 15:20:20 GMT</pubDate>
            <atom:updated>2021-05-10T15:23:08.120Z</atom:updated>
            <content:encoded><![CDATA[<p>Analysing web traffic from e-commerce</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b9PlXGgaCZ5jFqDCh8CW9w.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@rupixen?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">rupixen.com</a> on <a href="https://unsplash.com/s/photos/e-commerce?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Conversion rate optimization is a process to understand what drives, stops, and persuades users to a website. The objective is to give users the best user experience possible and to increase website sales or minimize acquisition costs.</p><p>The main focus of this blog is to analyse traffic sources and marketing channels that lead to conversion rates. To do that we’ll use MySQL Workbench.</p><p>Let’s see a list of common digital marketing channels:</p><ul><li><strong>Organic traffic</strong> includes traffic that comes from search engines. In this field, examples are Google, Bing, Yahoo etc. It occurs when visitors or potential customers discover our website by searching for keyword, phrase or product.</li><li><strong>Paid search </strong>This channel includes all traffic that comes from paid search ads on search engines. Such campaigns can be launched on Google AdWords and Bing Ads.</li><li><strong>Email</strong> Includes all traffic that comes from emails (email marketing campaigns, order confirmation emails, newsletters, etc.).</li><li><strong>Social media </strong>includes all traffic that comes from social media channels, such as Facebook or Twitter. It can be free organic traffic got from regular social media posts, or paid traffic from social media ads.</li><li><strong>Direct </strong>Includes all traffic from users that are brought directly to your website when typing in your web address URL in the browser or clicking on the URL in their bookmarks.</li><li><strong>Referrals</strong> usually allude to all traffic that doesn’t come from search engine, i.e traffic that comes from another website by clicking on a <em>http</em> link.</li></ul><p>Consider the e-commerce diagram in the picture below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UwUNdLqXZm-YfoyL.png" /></figure><p>Our database includes 6 related tables, containing information about <strong>website activity</strong>, <strong>products</strong>, and <strong>orders</strong>. We can clearly see the relationship between those tables, identified by the primary key and foreign keys.</p><p>The database has information about transactions that occur between 2012 and 2015. In total, the sessions and orders totalized 472,871 and 32,313 respectively. For each year we also count the number of sessions and orders per year as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zDmwi893wfoEjhK9_oVxIQ.png" /><figcaption>Total sessions and orders per year</figcaption></figure><p>Our main goal is to use SQL query to understand which channels are driving traffic to the e-commerce website and what channel is being used and driving the highest conversion rate.</p><p>To answer these questions our focus will be on <strong>website_sessions</strong>, <strong>website_pageviews </strong>and <strong>orders tables</strong>.</p><p>First, take a look at the <em>website_session</em> table. By using this query <strong>SELECT * FROM</strong> website_sessions <strong>WHERE</strong> website_session_id = 1020 the result displays 9 columns as follow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*oKZkOmJa3whfX3BfBgbrRg.png" /><figcaption>Website_session table</figcaption></figure><pre><strong>website_session_id </strong>is the primary key of the website sessions table.</pre><pre><strong>created</strong>_<strong>at</strong> is a timestamp indicating when that session takes place.</pre><pre><strong>user_id</strong> is linked to the cookie in a user’s browser used to track users across multiple sessions.</pre><pre><strong>is_repeat_session</strong> is a binary number. represented by 0 or 1 depending on whether or not this user has been to the website before.</pre><pre><strong>utm_source</strong>,<strong> utm_campaign </strong>and<strong> utm_content </strong>are tracking parameters that used to measure our paid marketing activity.they are appended link tags to our website URLs. </pre><pre><strong>Device_type</strong> indicates whether the user is on their computer or if they’re on a mobile device.</pre><pre><strong>http_referer </strong>indicates where traffic is coming from.</pre><p>We can say that the user_id 1018, access our website page on 2012–03–26 from a paid search engine and from a desktop.</p><p>From the<em> website_pageviews </em>table, by using the following query <strong>SELECT * FROM</strong> website_pageviews <strong>WHERE</strong> website_session_id = 1020 it includes 4 columns:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*a80eCIaiVY3uNBPLdwIZPw.png" /><figcaption>website_pageviews</figcaption></figure><pre><strong>website_pageviews - the</strong> Website_pageview table is basically the page views that a user saw when they were on the e-commerce website.</pre><pre><strong>created_at - </strong>is a timestamp indicating when that pageview happened.</pre><pre><strong>website_session_id - </strong>note that this column is a primary key on website_session table and in the website_pageviews it corresponds to the foreign key, so when we want to use those two table together we will use a join clause.</pre><pre><strong>pageview_url - </strong>means that an user first landed on the<strong> home </strong>page in a specific time and then later he/she went to the <strong>products </strong>page then clicked through to the <strong>original Mr. Fuzzy</strong> page then clicked through to the<strong> cart </strong>then to the <strong>shipping </strong>page, the <strong>billing page an</strong>d finally they landed on <strong>thank you for your order</strong>. This is important for conversion funnel analysis.</pre><p>From the output above, we can say that the user_id 1020 landed on the /home page and 1 minute later she/he went to the /productspage, then 4 minutes later he clicked on /originl-mr-fuzzy, and then after 3 minutes, he/she add the product to the /cart<strong> </strong>and when she clicked on<strong> </strong>/shipping<strong>, </strong>he/she abandon the purchase.<strong> </strong>So why did this happened? it was because the user was surprised by additional costs? (see this <a href="https://www.bolt.com/resources/ecommerce-checkout-best-practices/">article</a> for more insights). This is a type of question important for conversion funnel analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FmXeaDjrP9Q4-3CY.png" /><figcaption>A common e-commerce flow shop. Source: google.com</figcaption></figure><p>In the case of the <em>orders</em> table, where the sales are tracked, by using the following query <strong>SELECT * FROM</strong> orders it displays 8 columns:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*Cd9H6kAo7lJHZgBgYquLGQ.png" /></figure><pre><strong>order_id - </strong>is the number of the transaction</pre><pre><strong>created_at - </strong>is a timestamp indicating when that order happened.</pre><pre><strong>website_session_id - </strong>this column is a primary key on website_session table and in the order_id it corresponds to the foreign key, so when we want to use those two table together we will use a join clause.</pre><pre><strong>user_id</strong> is linked to the cookie in a user’s browser used to track users across multiple sessions.</pre><pre><strong>primary_procut_id - </strong>indicats the product that a customer puts in their cart first. It has 4 different numbers rnge between 1 to 4.</pre><pre><strong>item_purchased - <br>price_usd </strong>is the price of the products in dollars <strong><br>cogs_usd </strong>is the cost of goods sold in dollars</pre><p>From our example, by using the query <strong>SELECT * FROM</strong> orders <strong>WHERE</strong> website_session_id = 1020 we get this result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*iZIx6_3j3ExpZLpaosJO0w.png" /><figcaption>orders</figcaption></figure><p>The table didn&#39;t return any information because the user_id 1020 did not complete the order as we deduce previously.</p><h4><strong>Channels that drive traffic to the website</strong></h4><p>Using the query, we obtain the following output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U6zsItUfXY9M3-_CFHsAgQ.png" /></figure><p>The result shows that we have different categories in each <em>utm</em> parameters. For example, <em>utm_source</em> has 3 different categories: <em>bsearch</em>, <em>gsearch </em>and <em>socialbook. </em>The same interpretation can be made for the other two <em>utm</em>. All these <em>utm</em> parameters are paid campaign.</p><p>An important thing to note is the null value that appears in the first row. Those could be traffic that is not driven by a paid campaign or possibly they forgot to put tracking parameters on those campaigns.</p><p>So which channels drive traffic to the website? we can answer the question by using this query:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CQjrNfRH6a4e8JCzJ6nacw.png" /></figure><p>The output shows us clearly that <em>gsearch</em> source, from <em>nonbrand</em> campaign category, contribute to the highest sessions followed by the null value which corresponds to traffic not paid.</p><p>Now that we know that <em>gsearch nonbrand </em>drives the most volume in session, we can ask how many of this session is converted into an order. Let’s do this by using the following query:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n3zn75PlchgrBP4aeKEpqg.png" /></figure><p>So for our example,<em> </em>our website received 282,706 sessions from <em>gsearch nonbrand </em>and was made 18,822 orders.</p><p><strong>But what exactly is <em>branded</em> and<em> nonbranded </em>keywords<em>?</em></strong></p><p>A ‘<em>branded</em>’ keyword usually includes the brand name of the company or some variation of it. These are different from <em>nonbrand</em> keywords which are keywords that do not relate to the brand name.</p><p>A comparison analysis of <em>nonbranded/brand</em> keywords and traffic is important for two reasons:</p><ul><li>Because particularly for large brands, branded keywords search in the engines indicates that the user knows the company.</li><li>Because it often represents the majority of our website’s new visitors and unique visitors. Most importantly, these visitors may not already know about our brand.</li></ul><p>But before we move to the analyse of the<em> brand/nonbranded</em> keywords, let’s get the conversion rate. For a better understanding, it would be more useful if we calculate the conversion rate over time from 2012 until 2015 particularly for <em>gsearch</em> source which has the highest number of sales and orders. Consider the following output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ex_hO8HfUOQlxM-RAwlSaA.png" /><figcaption>Conversion rate</figcaption></figure><p>From the result above we can see that over time both sessions and orders are increasing. But from these values, we can also see that a lot of users that visit the website, few are actually making a purchase (order). In the perspective of conversion rate, we see an increase from 3% in 2012 to 7% in 2014, this doesn&#39;t mean that the sessions are turning into sales.</p><p>This means that traffic is not resulting in more sales. Instead, it results in ad spend derived from the paid campaign.</p><p>Our next step should be to break down the <em>gsearch </em>source into campaign which is categorized into two keywords:<em> brand</em> and <em>nonbrand. </em>Using the following query, we get this result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PO9k-a7AMr5F6qTEB2DVZQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*Th5KG9E-gR7IL7Ri3CjWPQ.png" /></figure><p>Notice that, as we write at the beginning of this article that paid traffic indicates that a visitor/customer came to our website from a paid search ads on search engine, what we can deduce from the table is that:</p><ul><li>Besides our visitors are searching from our paid <em>gsearch</em> engine, these visitors may not know about our brand name and accidentally they find our website by searching a product in those engines.</li><li>That’s why<em> nonbrand</em> traffic has a higher number of sessions than <em>brand </em>traffic. We can think of them as the website’s new visitors for example.</li><li>For those who know the <em>brand</em> of our e-commerce company, besides the increased session over time, it still very low compared to nonbrand session.</li></ul><p>We are getting closer to the final step. Now we are going to analyze the type of device our users are using to access our website through the <em>gsearch </em>engine. Using the query below we get the output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4aFUORGy7zZcvHjASVyyew.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*1ApxF5efkdQ-pW1yeqSXCA.png" /></figure><p>What we can interpret from the result table, is that desktop is being by far the channel that users majority use to access the website. However, this doesn&#39;t turn the session into sales. We have users that access our website by using desktops however the orders are extremely low compared to the session. An analysis that is important at this point would be to look at funnel sales. For that, we would need the <em>website_pageviews</em> table, but this could be referenced in another article to not make the blog too long.</p><h4>Summary</h4><p>From our web traffic analysis, we saw that the top sources that drive most sessions are: <em>gsearch nonbrand</em>, <em>none</em> (which indicates traffic unpaid) and <em>bsearch nonbrand</em>.</p><p>Based on the results we obtain so far, we cannot give a precise conclusion but we can say that our brand is not being noted and also, the company should cut ad spend and look to our unpaid ads that are increasing over time. Besides, we will need more metrics to add to this information for example how sales are growing over time, what’s the cost of sales, look at abandoned cart data, purchase funnel and most popular products.</p><p>Thanks for reading, my name is Kueila Ramos and I have been self-learning Data Science for about 2 years. I hope that you find this blog useful. If you have any suggestions, please let me know.</p><h4><strong>Reference</strong></h4><p>Keyword Basics: Branded vs. Non-branded — <a href="https://www.risdall.com/our-thoughts/keyword-basics-branded-vs-non-branded-provided/">https://www.risdall.com/our-thoughts/keyword-basics-branded-vs-non-branded-provided/</a></p><p><a href="https://venturi-web-design.com/calculate-sales-conversion-rate/">How to Calculate Sales Conversion Rate &amp; Lead Value</a> — <a href="https://venturi-web-design.com/calculate-sales-conversion-rate/">https://venturi-web-design.com/calculate-sales-conversion-rate/</a></p><p>Designing An eCommerce Checkout Flow: A Must For Your Online Store — <a href="https://makewebbetter.com/blog/ecommerce-checkout-flow/">https://makewebbetter.com/blog/ecommerce-checkout-flow/</a></p><p><a href="https://www.bigcommerce.com/blog/ecommerce-branding/#1-better-serve-your-customer">Ecommerce Branding: 11 Strategies To Build Your Brand</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39e108cadfa2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL query with Inner Join, Business questions and visualization with Tableau— Part 3]]></title>
            <link>https://kueilaramos.medium.com/sql-query-with-inner-join-business-questions-and-visualization-with-tableau-part-3-229fcd7f8aa3?source=rss-99cb0af6393e------2</link>
            <guid isPermaLink="false">https://medium.com/p/229fcd7f8aa3</guid>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[innerjoin]]></category>
            <category><![CDATA[business-questions]]></category>
            <category><![CDATA[tableau]]></category>
            <dc:creator><![CDATA[Kueila Ramos]]></dc:creator>
            <pubDate>Mon, 19 Apr 2021 12:43:44 GMT</pubDate>
            <atom:updated>2021-04-19T13:41:41.754Z</atom:updated>
            <content:encoded><![CDATA[<h4>Understanding Business requirements by using SQL Inner Join, Venn Diagram and Tableau</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U6CDgIAMt2l2vDoFqhwv6A.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@goumbik?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Lukas Blazek</a> on <a href="https://unsplash.com/s/photos/technology?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>This blog is related to part 3 of 4. In the previous <a href="https://kueilaramos.medium.com/sql-querying-on-a-bank-database-part-2-eb15ba474755">article</a>, we’ve focused on a basic query involving a single table. We know that a relational database consists of multiple related tables linked together using common columns and the process behind it is called Normalization.</p><p>As we discuss in <a href="https://kueilaramos.medium.com/understanding-relational-database-part-1-4a56c29f9b09">Understanding Relational Database article part 1</a>, the Normalization process makes data storage more efficient and avoids problems such as data redundancy.</p><p>However, to answer business questions, we need to recombine the data from the tables. This means that we must write JOIN queries.</p><p>The general syntax of a Join clause is as seen below:</p><pre><strong>SELECT </strong>column_name, expression<strong><br>FROM </strong>table1 <strong>as </strong>t1<strong><br>[INNER |{LEFT|RIGHT}[OUTER]] JOIN </strong>table2 <strong>as</strong> t2<strong> ON </strong>join<strong> </strong>condition<strong>;</strong></pre><p>If the join condition uses the equal operator (=) and the column names in both tables used for matching are the same, we can use the USING clause instead:</p><pre><strong>SELECT</strong> value_expression<br><strong>FROM</strong> table1 <strong>as</strong> t1<br><strong>[INNER |{LEFT|RIGHT}[OUTER]] JOIN </strong>table2 <strong>as</strong> t2 <strong>USING</strong> (column_name);</pre><p>I am using MySQL system but there are many other variants available, like PostgreSQL, SQLite, Oracle to mention a few examples. Across the different languages, the syntax can change a little bit, but the main concepts remain the same.</p><p>Join is a technique of combine data between one (self-join) or more tables based on values of the common column between the tables.</p><p>Combining data is straightforward. We simply specify which tables are involved and how the tables are connected. This means that, in the FROM clause, we write the name of the first table<strong> (table1) </strong>that we want to take columns from. Then, we use the JOIN keyword, followed by the name of the second table<strong> (table2)</strong>.</p><p>Next, the ON or USING clause (join condition) is used to query on which columns data should be joined (usually, this is an ID). However, keep in mind that the columns on which we join the data are not always in the form of an ID. They also don’t need to have the same name.</p><p>To understand the process, in this article we will explain how a INNER JOIN clause works.</p><h4>INNER JOIN clause involving two tables:</h4><p><strong>Consider the business request:</strong> List the customer name and customer id of everyone who bought something in September 2017.</p><p>The first step is to understand our data. Let’s take a look at how the sales data transaction database is structured:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*bTI_A7AItBY2xMJ-HROxCQ.png" /><figcaption>Database schema</figcaption></figure><p>We use <strong>SHOW</strong> tables command to display the tables we have in our sales database:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*n0YCMLwJCifkqGgQILiX2Q.png" /><figcaption>Tables in the sales order database</figcaption></figure><p>To answer the business request we first must identify the tables involved. We can see it through the <strong><em>Entity Relationship Diagram (ERD)</em> </strong>below, it show us how the tables are connected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/309/1*H2-N-WWUe_UpVqL_nVY2sg.png" /><figcaption>Relation between orders table and customers table</figcaption></figure><p>In this case, the two tables involved are orders table and customers table. The<em> Orders</em> table contains just theCustomerID to identify the specific customer. Customer name and other additional data are stored in the customers<em> </em>table along with the CustomerID.</p><p>To get the answer we want, we can use the following query:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9cf2b9b787d20235546ce7bf75487537/href">https://medium.com/media/9cf2b9b787d20235546ce7bf75487537/href</a></iframe><p>The partial output is as follow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*tBYhq0jKu2tAeptIf9sPWQ.png" /></figure><p>What we are doing is:</p><ul><li>We enter the table names — ordersand customers — in the FROM line connected by a INNER JOIN clause. The INNER JOIN clause is used because we want to retrieve an exact match between those two tables.</li><li>Second, we tell the DBMS which columns are matched in each table. In this case, we match CustomerID<em> </em>in the orderstable to the CustomerID in the customers table [ON o.CustomerID = c.CustomerID]. Remember, most of the time the column names will be the same as in this example, but they could be different. Also remember, if we don’t specify any join condition, most query systems will produce a <strong>cross join</strong>, where every row in one table is paired with every row in the other table.</li><li>The letters C and O are the table<em> </em><em>alias</em> for simplicity. Since the column CustomerID is used in both tables, it would not make sense to write CustomerID = CustomerID . So to keep track of which column we want, we must also specify the name of the table: o.CustomerID and c.CustomerID</li><li>WHERE clause is used to specify the order date we want to get the information, and ORDER BY clause is used to sort the result. In this case, we sort the values by orderdate. However, if we want to sort by CustomerID, the result would be:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*OfO37Emk4OltGG5u3cyhDQ.png" /></figure><p>The output shows us the purchases each customer made between 2nd and 30th September. For example, Suzanne made a purchase on the following days: 02, 03, 10, 17, 24, 25, 28 and 30 of September.</p><ul><li>Because some customers might have made several purchases on the same day at different times, the DISTINCT clause was used to delete the duplicate rows. If we don’t include the DISTINCT clause, the result would be as follow:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*EaEDoCYOF0PZn_e-OlFQfQ.png" /></figure><p>For example, Suzanne made 2 purchases on 02 September. We can think that she made a purchase in the morning and then in the afternoon she made another purchase.</p><h4><strong>So, what is an INNER JOIN clause?</strong></h4><p>The INNER JOIN clause compares each record from the first table with every record from the second table. If values in both rows cause the join condition evaluates to true, the inner join clause will result in the set of record that match both tables.</p><p>To put this in a simple way, we can think of intersection in set theory. Suppose we want to examine two sets of numbers. The first set of numbers is A = {1, 5, <strong>8</strong>, 9, 32, <strong>55</strong>, 78}. The second set of numbers is B = {3, 7, <strong>8</strong>, 22, <strong>55</strong>, 71, 99}. The intersection of these two sets of numbers is the numbers common to both sets: 8 and 55.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/1*h7Xrlf67zYWlyWOXJuoi5A.png" /></figure><p>So, for our business request example the intersection of the orders table and customers table is the column common to both sets: CustomerID . The <em>Venn Diagram</em> is illustrated as follow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*agNskq24xyq3aIGdPahnzA.png" /></figure><h4><strong>INNER </strong>JOIN clause<strong> involving more than two tables:</strong></h4><p>In the<em> sales order database,</em> we know that the orderstable and customers table are linked by CustomerID. The diagram below shows us that we have the orders and order_details tables linked using the orderNumber column, the order_details and the products table linked using productnumber column:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*ZM95oAXyyiJ6LZtWoumPow.png" /></figure><p>We need the <em>order number</em>, <em>order date</em>,<em> customer first name</em> and <em>last name</em>, <em>order amount</em> and <em>product name</em>. To translate this we could say:</p><ul><li>From customers table joined with orders on CustomerID in the orders table matching CustomerID At the customer table,</li><li>Then joined with the order_details table on orderNumber in the orders table matching orderNumber in the order_details table,</li><li>And then finally joined with products table on productNumber in the products table matching productNumber in the order_details table.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae4297be979d0f97e3e8e358a5e3ab40/href">https://medium.com/media/ae4297be979d0f97e3e8e358a5e3ab40/href</a></iframe><p>In this query, we use INNER JOIN and two different approaches to link the tables together with both producing the same result set. We use an USING clause in the first query and then we use an ON clause.</p><p>Once we execute the above statements, we can see the partial result set of the data in the following image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GGJ9gZL0DKhUHWj9nwVsSQ.png" /><figcaption>Partial query result set</figcaption></figure><p>Remember that INNER JOIN selects all rows from both tables as long as there is a match between the columns in both tables. So, In this query, we request specific information about customers that have ordered or purchased a product on a specific date. That’s why we use an inner join.</p><p>To get customers who didn&#39;t order we must use another type of join. These are called OUTER JOIN<strong> </strong>which will be explained in article part 4.</p><blockquote><strong>More Business questions answered with SQL queries: Customer and product analysis</strong></blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d1da69d30ab04f76000ea656f518d43/href">https://medium.com/media/2d1da69d30ab04f76000ea656f518d43/href</a></iframe><p>The result of the above query is shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*y90nu-q55_jI_rViY_SKuQ.png" /><figcaption>Result set</figcaption></figure><p>The graphical representation of the query above is shown as follow in the Dashboard obtained from Tableau:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*crProIVlVuoIIlj_bYgxWw.png" /><figcaption>Graphical representation of business question in tableau</figcaption></figure><h3>Summary</h3><p>We conclude that Normalization splits data into tables that can be stored and searched more efficiently. In another hand, queries are the reverse operation. The process of combining tables is related to Joins. which means that to get information from multiple tables we need to writing JOIN queries.</p><p>Be mindful that any time we use multiple tables, we must join them together. The joined tables also create a huge query. If we don’t specify any constraints, most query systems will produce a <strong>cross join</strong>, where every row in one table is paired with every row in the other table.</p><p>In the next blog, the topic will involve OUTER JOIN clause. Thanks for reading and I hope that you find this blog useful.</p><h3><strong>Book Reference</strong></h3><ul><li>John L. Viescas, Michael J. Hernandez (2014). SQL Queries for Mere Mortals, A Hand on Guide to Data Manipulation in SQL.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=229fcd7f8aa3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL Querying on a Bank Database — Part 2]]></title>
            <link>https://kueilaramos.medium.com/sql-querying-on-a-bank-database-part-2-eb15ba474755?source=rss-99cb0af6393e------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb15ba474755</guid>
            <category><![CDATA[banking]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[query]]></category>
            <category><![CDATA[mysql]]></category>
            <dc:creator><![CDATA[Kueila Ramos]]></dc:creator>
            <pubDate>Tue, 13 Apr 2021 13:31:53 GMT</pubDate>
            <atom:updated>2021-04-19T13:42:38.854Z</atom:updated>
            <content:encoded><![CDATA[<h3>SQL Querying on a Bank Database — Part 2</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PcVV-Stq79lbp4y8tYcdqA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@casparrubin?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Caspar Camille Rubin</a> on <a href="https://unsplash.com/s/photos/mysql?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>This blog is related to part 2 of 4 (see part 1 — <a href="https://kueilaramos.medium.com/understanding-relational-database-part-1-4a56c29f9b09">Understanding Relational Database </a>). We will focus on querying and reading data from an existing database, as part of my learning path in understanding SQL. We will be using the MySQL Workbench server and a sample bank database which will be available on my Github repository.</p><p>The main focus will be to formulate queries using SELECT, FROM, WHERE, GROUP BY, HAVING and ORDER BY clauses to retrieve data from a single table using MySQL connected to DBeaver.</p><h3><strong>Introducing the SELECT statement</strong></h3><p>The command most used in SQL statement is the SELECT clause, which is used to retrieve data from tables stored in a database. A simple version of the command contains the three basic parts: SELECT, FROM and WHERE. These parts match the basic questions needed by every query:</p><pre><strong>SELECT columns       -&gt; What output we want to see?<br>FROM table(s)        -&gt; What tables are involved?<br>WHERE condition      -&gt; What are the constraints?</strong></pre><p>Besides the SELECT and FROM clauses, the SELECT statement can contain many other clauses. Regardless of which RDBMS we are using, the list below is the big 6 elements of a SELECT statement:</p><pre><strong>SELECT </strong>[DISTINCT|ALL]<strong> (*, column [AS alias]...)   <br>FROM </strong>tablename <strong>      <br>[WHERE </strong>condition<strong>]<br>[GROUP BY </strong>group_by_expression<strong>]<br>[HAVING </strong>group_condition<strong>] </strong> <strong>   <br>[ORDER BY</strong> columname<strong>]</strong></pre><p>The capitalized words SELECT, FROM, WHERE and so forth are keywords (words with a predefined meaning). Each keyword is referred to us as a clause:SELECT clause, FROM clause, WHERE clause and so on).</p><p>SELECT is the primary clause of the SELECT statement followed by FROM clause. We use SELECT to specify the columns we want to include in our result set. The columns are drawn from the table (or view) we specify in the FROM clause. (we can also draw them from several tables simultaneously, which is discussed in <a href="https://kueilaramos.medium.com/sql-query-with-inner-join-business-questions-and-visualization-with-tableau-part-3-229fcd7f8aa3">part 3</a> and part 4) we can also use <strong>aggregate functions</strong>, such as <em>Sum(salary)</em>, or <strong>mathematical expressions</strong>, such as <em>Quantity * Price</em>.</p><p>In the simplest form, the SELECT statement contains the syntax for selecting columns, selecting rows, grouping data, joining tables, and performing calculations.</p><h4><strong>How to use simple </strong><strong>SELECT statement to query data from a single table with </strong><strong>SELECT clause:</strong></h4><pre><strong>SELECT </strong>*<strong> FROM </strong>customer; -&gt; select all information from customer table (columns and rows)</pre><pre><strong>SELECT </strong>city <strong>FROM </strong>customer -&gt; select only one column from customer table</pre><pre><strong>SELECT </strong>city, cust_id<strong> FROM </strong>customer -&gt; select specific columns from customer</pre><pre><strong>SELECT</strong> DISTINCT CustState <strong>FROM</strong> customer -&gt; select unique values of custstate from customer, without duplicates</pre><p>To have the SELECT statement return all data from a specific table, we type an asterisk (*) . It is a great way to quickly see what data a table contains. This statement retrieves all data stored in the customer table.</p><p>When specifying more than one column in the SELECT clause, commas should separate the columns listed. Keep in mind that if we forget a comma, the system interprets the subsequent field name as a column alias and we don’t get the results we intended.</p><p>Running <strong>SELECT * FROM</strong> table without using a WHERE clause will return the entire table (all columns and all rows). Be cautious, in a large database we should limit our data.</p><p>Now that we know how to select columns from a table, we can look at some other operations such as how to use a column alias, arithmetic operations and eliminate duplicate output.</p><p>We’ll begin with relatively easy queries by presenting queries from our bank database to show the basics of creating a query.</p><p>Consider a typical banking diagram in managing the institution’s data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*QbK__dNBuFoXyIQ7pBQFJg.png" /><figcaption>EER Diagram</figcaption></figure><p>In this case, our database includes 11 related tables, containing information about:</p><ul><li>Customers (Cust_id, Address, etc.)</li><li>Business (employee, account, etc.)</li><li>Product and so on.</li></ul><p>Each table contain information organized into <em>tuples </em>(rows or record) and<strong> </strong><em>attributes</em><strong> </strong>(columns or fields). For example, our<strong><em> </em></strong><em>account </em>table contains 11 columns and 24 rows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*v1RwZT2-f8hgrHxfsZ2XcA.png" /><figcaption>Partial result set</figcaption></figure><ul><li>Each column contains an attribute related to the bank account:ACCOUNT_ID, AVAIL_BALANCE, CLOSE_DATE, CUSTOMER_ID etc.</li><li>Each row corresponds to one specific account (example: ACCOUNT_ID = 2, has an available balance = 500, owned by customer_id number 1 and this account is a saving account(SAV).</li></ul><p>As we know, from the previous <a href="https://kueilaramos.medium.com/understanding-relational-database-part-1-4a56c29f9b09">article</a>, normalized tables contain <strong>Primary Key</strong> <strong>(PK)</strong> and <strong>Foreign Keys (FK). </strong>The ACCOUNT_ID column is known as a primary key, which serves as a unique identifier for each record in the <em>account </em>table. CUST_ID and OPEN_BRANCH_ID that appears in the table corresponds to the foreign key.</p><p>Consider the first query using<strong><em> </em></strong><em>product_type</em><strong><em> </em></strong>table and <em>pty</em> as alias&gt;</p><pre><strong>SELECT </strong>*<strong> FROM </strong>product_type; -&gt; select all columns</pre><pre><strong>SELECT</strong> pty.* <strong>FROM</strong> product_type pty -&gt; retrieve all columns</pre><pre><strong>SELECT</strong> pty.prodyct_type_cd, pty.name <strong>FROM</strong> product_type pty -&gt; select two specific columns using pty as alias</pre><p>The above statements are equivalent. Pty is used as an alias to <em>product_type</em> table. The output is as follow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*At9dSduDBAN1h-mRezzuow.png" /><figcaption>Partial query result</figcaption></figure><p>Getting information on the <em>employee</em> table using Eas an alias for employee:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*IPvpVKWCMgNmOV5HrvEQYw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/1*k8pNwFl7Dcl3VC8FfcK6ow.png" /><figcaption>Partial query result</figcaption></figure><p>What is happening is that the alias Ecan directly follow the table name by writing <em>employee </em>E in the FROMclause or can follow the AS keyword as shown in the following example below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*rgTUj94i7iL--7_zQD3MOg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/1*ZzZRX5RbfM-hAuFqHb4gIw.png" /><figcaption>Partial query result</figcaption></figure><p>In this particular example what we are doing is asking the system to do the following:<em> for each employee, retrieve the employee’s first and last name and the first and last name of his/her immediate supervisor.</em></p><p>This question involves only <em>employee </em>table<em>.</em> All of the information about the question we want to see and the constraint is based on columns in the <em>employee </em>table.</p><p>In the example, we use a string function CONCAT to concatenate the two-column name FIRST_NAME and LAST_NAME in the SELECT clause. The first concatenation takes EMPLOYEE_NAME as an alias for the column header, the second concatenation takes SUPERVISOR_NAMEas an alias.</p><p>In the FROM clause, we can think of E and Sas two alias representing different copies of the <em>employee </em>table. E represents employees in the role of subordinates and S, represents employees in the role of supervisors.</p><p>In the WHEREclause, we joined the two copies. Notice that there is only one <em>employee relation</em>, and the join condition is meant to join the relation with itself by matching the tuples (rows) that satisfy the join condition E.EMP_ID =S.SUPERIOR_EMP_ID.</p><p>Whenever one or more aliases are given to a relation, we can use these names to represent different references to that same relation.</p><blockquote>Note: SQL use operators which are reserved keywords used in the WHEREclause of a SQL statement to <em>perform arithmetic</em><strong> </strong>(- , + , / , % , *)<strong> , </strong><em>logical operators </em>(LIKE, AND, OR, NOT, IN, BETWEEN, ALL, EXISTS etc)<strong> </strong>and <em>comparison operations</em><strong> </strong>(=, &gt;, &lt;, ≥, &lt;=, &lt;&gt;).</blockquote><p><strong>Let’s make more questions involving more combination of keywords:</strong></p><ol><li>Get the names of the employee (s) who were hired in 2002 and their respective supervisor name.</li><li>List employees whose names are Michael or Rick or Jane.</li><li>Get employees whose first name starts with &#39;s’ and works in Dept_ID = 1.</li></ol><p>Notice the business questions is a little vague, so we can choose which columns we want to see in the output. To answer these questions we can select columns such as FIRST_NAME , LAST_NAME , START_DATE and DEPT_ID.</p><pre><strong>1. Get the names of employee (s) who was hired in 2002 and they respective supervisor name</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*iCnvIVov6hz2HD21ySC3Vw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*W52qegl_08-w_WHYSSz0bg.png" /></figure><p>The table we want to retrieve information is the <em>employee</em> table. The criteria are defined in WHERE keyword. The WHERE clause will select all rows that meet the join condition E.EMP_ID =S.SUPERIOR_EMP_I and the criteria YEAR(START_DATE = &#39;2002&#39;) .</p><p>If we don’t specify YEAR and we just use START_DATE = &#39;2002&#39; we get an error incorrect DATE value: &#39;2002&#39; because actually, the format of the column is YYYY-mm-dd. the YEAR is used to get only the year without specifying the month or day.</p><p>The ORDER BYclause sorts the output rows. In this case, we use 1 to indicate that we want to order the output by START_DATE column since it is in the first position in the select query. The default sorts the output in ascending order ASC, adding the keyword DESC results in a descending sort.</p><pre><strong>2. List employees whos names are  Michael or Rick or Jane</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*rXTImcDy07vmxwZpE_ME4Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/309/1*i1rOI07oGWv3ah7tCnqi3A.png" /></figure><p>The IN operator allows us to test multiple possible values options. The syntax is: <strong>WHERE </strong>expression <strong>IN</strong>(value1, value2 ...valueN) .</p><p>In the example, we create a condition that checks if a value is included in a list of multiple options. It returns all rows from the <em>employee</em> table where the FIRST_NAME is either &#39;Michael&#39;, ‘Jane&#39;, or ‘Rick&#39;.</p><p>The IN condition is used to help reduce the need to use multiple OR conditions in SELECT statement. It works with values of all data types for example, with character, with numeric values and also using NOT operator.</p><pre><strong>3. </strong> <strong>list employees whose first name starts with ‘S’ and works in Dept_ID = 1.</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*36o6Y3MsoqpYmKqcYDAYiA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/417/1*hnGINS34bNaDI_enfnLfNg.png" /><figcaption>Query result</figcaption></figure><p>Here we are using the operator LIKE in the WHERE clause to find all <em>employee</em> whose FIRST_NAMEstarts with ‘S’. The operator allows us to perform pattern matching against a string or date format with the use of wildcard characters:</p><ul><li>Percent sign % matches any sequence of characters;</li><li>Underscore _ represents exactly one single character.</li></ul><h4><strong>SQL GROUP BY clause</strong></h4><p>The GROUP BY clause is used in a SELECT statement to divide rows in a table into smaller groups. Then use the group function to return summary information for each group.</p><pre><strong>SUM()- </strong>returns the total sum of a numeric column.<br><strong>AVG()-</strong> returns the average value of a numeric column.<br><strong>MIN()- </strong>returns the smallest value of the selected column.<br><strong>MAX()-</strong> returns the largest value of the selected column.<strong><br>COUNT()- </strong>returns the number of rows that matches a specified criteria.</pre><p>The figure below illustrates an example of how GROUP BY works with SUM , COUNT aggregate function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*tKZDHWqBlBJsHv93F9dwNg.png" /><figcaption>SUM aggregate function with GROUP BY</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*X0CAWl3_1K1e7pQFlyT-6g.png" /><figcaption>COUNT aggregate function with GROUP BY</figcaption></figure><p>Now let’s look at how we could use the GROUB BY clause with these aggregate function.</p><p>We might ask what is the total amount of money in an account in proportion to each type of different services (PRODUCT_CD)and also we want to know how many different accounts exist and the average of the available balance.</p><p>Recall that an aggregate function takes in multiple values and reduces them back down to one single value:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*9AvpHw8OqsRKPw1jvV3dXg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*1rg3GltDlNHkp3vR43H3AA.png" /></figure><p>In this case, COUNT function returns the total number of unique values in the account column which is equal to 24. The SUM function takes in all values without specifying a category and then return back the total sum account of 170,754.46. and the AVG gives us the average of the available balance. The ROUND function is used just to returns the values rounded in 2 decimals.</p><p>But this doesn&#39;t return value per category. To do so, we need to use a GROUP BY clause:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/437/1*4INpVs2bjERXsI6trukMug.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*MyM5r61pHFnovjmhrXJfxg.png" /></figure><p>In the SELECT statement, the rows are being grouped by PRODUCT_CD and then the COUNT, SUM, AVG being calculated for each PRODUCT_CD separately. If we did not include GROUP BY clause, i.e, if we omit the clause we would obtain only one row like the table below which is wrong:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/1*Pwqy_7PzWz-pMfncuDMuCA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*bMSC7nfQzXewzyXyh1-8Ow.png" /></figure><p>We could also use more than one column. Using the following query, we also selectOPEN_EMP_ID column:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*SnGZpQMvrwo-ub0yfLxnuw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*A4_phtHwiXWivs02cucqoQ.png" /><figcaption>Partial result set</figcaption></figure><p>To filter the result by only PRODUTC_IDwe must use WHERE before apply GROUP BY :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*3-sDK9537b5RP259gsDTpQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*zDmCyc-Q3ekuRzL-YkF8Nw.png" /><figcaption>Partial result set</figcaption></figure><p>So what we’re saying is, select PROUCT_CD, OPEN_EMP_ID, COUNT, SUM, AVG and filter PRODUCT_CD where the product is in &#39;CHK&#39; and &#39;SAV&#39; account, before we actually perform the GROUP BY on the PROUCT_CD and OPEN_EMP_ID (these columns are indicated by their position 1 and 2).</p><p>The ORDER BY clause means that we want to sort the value based on the positions of the columns selected. Keep in mind we could also sort the results by selecting the aggregate function by their positions or by referencing the entire function.</p><h4>SQL HAVING clause</h4><p>The WHERE keyword cannot be used with aggregate functions. It places conditions on the selected columns. An alternative way is to use HAVING clause which places conditions on groups created by the GROUP BYclause.</p><p>Looking at the above result, now suppose we want to group the types of services PRODUCT_CD and get only the types that the sum of the account is above 700. The query is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*wuuOs30ZcraEePZCSE3OIQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*2n09YX913ZIVrmaIBiODkQ.png" /></figure><h4><strong>Summary</strong></h4><p>We have concluded our second part of the article resumed into formulating queries for retrieving data from a <strong>single table</strong> using MySQL and DBeaver. We have covered an explanation about GROUP BY and HAVING clause. We learned about the difference between WHERE and HAVING clause with examples.</p><p>We covered the fact that the SELECTand FROM clauses are the fundamental clauses required to retrieve information from the database and that the remaining clauses — WHERE , GROUP BY and HAVING— are used to conditionally process and filter the information returned by the SELECT clause.</p><p>In the next blog, the topic will involve JOIN clause which includes works with more than one table.</p><p>Thanks for reading and I hope that you find this blog useful.</p><h4>Books References</h4><ul><li>John L. Viescas, Michael J. Hernandez (2014). SQL Queries for Mere Mortals, A Hand on Guide to Data Manipulation in SQL.</li></ul><h4>Link Reference:</h4><p>Technothenet: <a href="https://www.techonthenet.com/mysql/select.php">https://www.techonthenet.com/mysql/select.php</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb15ba474755" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Relational Database — Part 1]]></title>
            <link>https://kueilaramos.medium.com/understanding-relational-database-part-1-4a56c29f9b09?source=rss-99cb0af6393e------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a56c29f9b09</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[relational-model]]></category>
            <category><![CDATA[relational-databases]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Kueila Ramos]]></dc:creator>
            <pubDate>Fri, 02 Apr 2021 13:24:55 GMT</pubDate>
            <atom:updated>2021-04-19T13:31:34.891Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding Relational Database — Part 1</h3><h4>Understanding concepts of database Relational Model.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aTwZq7ceSHClNuAconBNig.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@mbaumi?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Mika Baumeister</a> on <a href="https://unsplash.com/s/photos/data-table?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>In this article part 1 of 4, we will take steps through a process of understanding the foundations of a Relational Database Model. <a href="https://kueilaramos.medium.com/sql-querying-on-a-bank-database-part-2-eb15ba474755">Part 2</a> is dedicated to query a database using MySQL as part of my learning path in understanding SQL.</p><p>In school, we often work using tools such EXCEL as the main source of data (spreadsheet downloaded from government data portals or academic sources) and SPSS or STATA for data analysis. Over the years I’ve been self-learning data science and working with data stored in a single spreadsheet. However, from the perspective of business analytics, we get into a whole different world. The overwhelming amount of data we need reside in databases.</p><p>When we talk about databases is a completely different picture as it involves a large amount of data and at this point, SQL becomes a necessary tool and I found myself struggling to understand some terminologies associate with them as I came from a business/economic background.</p><p>Database’s ecosystem includes concepts such as the <strong><em>Relational Model, Data Normalization,</em></strong> <strong><em>Entity Relationship Diagram </em></strong>and so on. As part of my learning process, in this blog, I will firstly look at some elementary database concepts without getting into too much detail, but sufficiently important to understand what is a database and its relationship with SQL. In another blog, I’ll use a database for the purpose of understanding these concepts in practice.</p><p><strong>Understanding the basic principles of the database in the Relational Model of data</strong></p><p>The digital era has brought three related implications: the rapid growth of electronic device, the massive growth of data and rapidly evolving methods for analysing data.</p><p>Data has become essential to every business and in almost every organization data have been gathered from several sources. For example, from an e-commerce website perspective, data can be split into two major components: a front-end that displays and collects information, and a back-end for storing the information.</p><p>Many people do not know much about database technology (including myself). We usually use a EXCEL spreadsheet which often leads to data inconsistency. The use of a spreadsheet may not cause a serious problem for a small data set, however, for a large organization, it could lead to serious errors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*4goH8R3RTsytyQmZswFxOA.png" /><figcaption>Database vs Spreadsheet</figcaption></figure><p>The common problems in spreadsheets are as follow:</p><p><strong>(1) No control of redundant data: </strong>Some people/organization often keep redundant data for convenience. This redundancy of data could make the data set inconsistent.</p><p><strong>(2) Violation of data integrity: </strong>Data integrity means consistency among the stored data.</p><p>Suppose we have two separate spreadsheet files that store student data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bIHMYtvzmQRu4-Yv2jmUDg.png" /><figcaption>Figure 1 — Spreadsheet</figcaption></figure><p>Take a look at the Grade Roster table in fig. 1: Student Mary Browmwith student ID number 4567 is stored more than once. This is called data redundancy, for some people, it could make data access convenient, but it can be harmful. For example, if Mary Browm changes her name or her major, then all her names and major stored in the system must be changed altogether.</p><p>For small data systems, it could be easier to solve. However, when the data system is huge, making changes to all redundant data is difficult if not impossible. To try to solve the redundancy problem, as a result, the entire data set could be corrupted.</p><p>We can also see that Alex Wilson received a grade in MKT211 however, we cannot find Alex Wilson in the Student Roster table. This means, the two rosters are not consistent. If we have data integrity control to enforce the rules, for example, “A student can’t receive a grade unless she/he has registered and paid tuition”, then we would avoid such violation of data integrity.</p><p>So to avoid these problems, database technology should be applied. A database is an organized collection of related data. It is an organized collection because in a database all data is described and related to one another.</p><p>There have been different types of databases over time: Hierarchical Database, Network Database, Relational Database, NoSQL Databases and so on. Databases follow a design model and the most popular is called <strong>Relational Model</strong> that was introduced by Edgar F. Codd.</p><p>The structure of Relational Model related to databases starts with a concept called tables referring to them as a collection of relations.</p><p>In a Relational Model, data are stored in a <strong>two-dimensional</strong> <strong>table</strong> or <strong>multiple tables related to each other</strong> through special key fields called <strong>Primary Key </strong>and<strong> Foreign Key</strong>. Informally, each relation resembles a table of c<strong>olumns</strong> and<strong> rows</strong>.<strong> </strong>In a formal relational model terminology, a column is called an <strong>attribute,</strong> a row is called a <strong>tuple </strong>and the table is called a <strong>relation.</strong></p><p>We sid before that, one of the key differences between databases and spreadsheets is that spreadsheets do not ensure the<strong> integrity </strong>of their stored data while databases must enforce data integrity. The following categories are the types of data integrity that must be enforced:</p><ul><li><strong>Domain integrity: </strong>enforces valid entries for a given attribute (column)by restricting the type, format, or range of values.</li><li><strong>Entity integrity: </strong>every tuple (rows) has a unique primary key that cannot be null. It simply means that there are no duplicate rows.</li><li><strong>Referential integrity:</strong> means that every Foreign Key in a secondary table matches a primary key that is in the parent table.</li></ul><blockquote>You may be asking, how databases can ensure data integrity?</blockquote><p>One important concept to understand is <strong>Normalization. </strong>In simple terms, to normalize a database means to design it in a way that:</p><p>1) Removes data redundancy</p><p>2) Ensure data integrity</p><p>Let’s take a practical example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*Gru5VChbKAYDF0tSeDghMQ.png" /><figcaption>Figure 2— Google source with some adaptation</figcaption></figure><p>Fig. 2 shows a Relational Database for three tables: Customer, Product and Purchase table.</p><p>Each table has two properties: tuples (rows) and attributes (columns). The intersection of a tuple and an attribute in a database is called a<strong> value.</strong></p><p><strong>An Attribute:</strong> represents each column in the table and they are the properties that define a relation. For example, from the relation schema above:</p><ul><li><strong>Customer table</strong> is the entity name of the relation, which have three attributes :<strong> CustomerID, Customer Name </strong>and <strong>Adress.</strong></li><li><strong>Product table </strong>is the name of the relation, which have three attributes: <strong>ProductID, Name </strong>and<strong> Price</strong></li><li><strong>Purchase table</strong> is the name of the relation, which have four attributes: <strong>TransactionID, CustomerID, ProductID, </strong>and<strong> Purchase date.</strong></li></ul><p><strong>Degree of relation:</strong> is the total number of attributes existing in the relation.</p><p><strong>Relation Schema:</strong> represents the name of the relation with its attributes.</p><p><strong>Cardinality: </strong>is defined as the total number of values from the underlying domain present in the table. For example, from the relation schema above all tables has 3 tuples in each one.</p><p><strong>Attribute domain: </strong>is the original sets of atomic values used to model data. This means that values in tables must have a consistent data type. The relational table itself follows particularly a <strong>defined datatype</strong> such as for example string, date-time, a number that describes the types of values that can appear in each attribute (these are represented by a domain of possible value).</p><p>From the perspective of analyzing data integrity:</p><p>Looking at figure 2 above, the <strong>Customer table</strong> and<strong> Product table</strong> has a unique primary key identified by ID. Database Management Systems will ensure the integrity of the data stored in those tables. For example, we cannot insert in the customer table the following 24221 because the CustomerID value 24221 already exists in the customer table. This constraint is called <strong>Entity Integrity.</strong></p><p>Information about different entities is stored in different tables. To access the data we need a way to navigate between them. Here Foreign key (FK) comes in hand. <strong>A Foreign key (FK) </strong>in a Relational Database matches a primary key in the parent database. with that said, if we look at the Purchase table we can identify two FK: <strong>CustomerID</strong> and <strong>ProductID</strong>.</p><p>The <strong>TransactionID</strong> is the Primary Key for the Purchase table, <strong>CustomerID</strong> is the Primary Key in the Customer table and <strong>ProductID</strong> is the Primary Key in the Product table. A Foreign Key is restricted to an existing parent key, this is a constraint called <strong>Referential Integrity.</strong></p><p>With that being said, some common examples of <strong>Relational Database Management System (RDBMSs) </strong>are Oracle, MS SQL Server, IBM, MySQL, SQLite, Microsoft Access, PostgreSQL, MariaDB to mention a few examples.</p><p>Without getting into detail on the nuances that differentiate each Relational Database Management System (which is not the goal of the article), we can say that even though the concepts of SQL is similar, the implementation of Syntax or Keywords is quite different from one to another.</p><p>However, they have in common the ability to control the access to a database and enforces database security which relies on confidentiality and integrity of the data stored.</p><p>As the database is managed by RDBMS, databases are accessed by a query language called SQL.</p><blockquote>SQL is a language used to connect or access the data stored in a Relational Database Management System by using sintax that allows us to query relational database by creating objects like, database, tables, read/write and access those tables.</blockquote><p>For example, if we work at a company that have databases storing customer information, employees information, sales information etc., as a data analyst user, we could form an SQL query (a question) that asks for exactly what we want to know about those data. The figure below shows us a representative example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*_1LPbFktLzuYhSXcCH1J6g.png" /></figure><p>A Database Management System (DMBS) is a computerized system that enables users to create and maintain a database, facilitates the process of defining, constructing, manipulating and sharing databases among various users and applications.</p><p>The standard SQL commands to interact with Relational Databases are CREATE, DROP, SELECT, INSERT, UPDATE, and DELETE. These commands can be grouped into 2 subsets:</p><p><strong>The Data Definition Language (DDL)</strong> which are statements used to define the structure of the database, create tables, specify their keys, data types, constraints of the data to be stored in the database and so on. The key, entity integrity, and referential integrity<strong> </strong>constraints are specified by the Data Definition Language.</p><p><strong>The Data Manipulation Language (DML) </strong>includes functions such as <strong>querying (read) </strong>the database to extract specific data, <strong>updating </strong>the database, <strong>insert new data</strong> and <strong>deletes</strong> data from a database so, collectively, these four functions are affectionately abbreviated as CRUD. The word, <em>created</em>, is generally used instead of <em>insert.</em></p><h3><strong>Conclusion</strong></h3><p>From a perspective of Relational Database what we can conclude is:</p><pre><strong>1. Every table must have at least one primary key which that cannot be Null to allows Entity integrity</strong></pre><pre><strong>2. Data model must be designed in a way it follows database normalization forms (you may heard about 1NF, 2NF, 3NF form)to allow us to reduce redundant data in a given database</strong><strong>.</strong></pre><pre><strong>3. Referential integrity must be mantained with help of Foreign Key</strong></pre><pre><strong>4. Table design should be organize in a way it follows domain integrity also called semantic integrity. Means that values in tables must have consistent data type.</strong></pre><pre><strong>5. Identify if a database holds an one-to-one relationship, an one-to-many relationship or a many-to-many relationship.</strong></pre><pre><strong>6. integrity constraints specified on the relational database schema must never be violated.</strong></pre><h3><strong>Summary</strong></h3><p>In this article, we covered some theoretical elements of Relational Database. We explain the difference between database and spreadsheet and important concepts of primary key and foreign key.</p><p>The next article will describe the basic SQL query in practice. Thanks for reading, I hope that you liked it and if you have any suggestions please contact me. Catch you on the next blog.</p><p><strong>Reference</strong></p><p><a href="https://digitalcommons.biola.edu/open-textbooks/1/">https://digitalcommons.biola.edu/open-textbooks/1/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a56c29f9b09" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Preparation & EDA of an E-commerce company using Python]]></title>
            <link>https://kueilaramos.medium.com/data-preparation-eda-of-an-e-commerce-company-using-python-374f038dcbc2?source=rss-99cb0af6393e------2</link>
            <guid isPermaLink="false">https://medium.com/p/374f038dcbc2</guid>
            <category><![CDATA[exploratory-data-analysis]]></category>
            <category><![CDATA[e-commerce-market]]></category>
            <dc:creator><![CDATA[Kueila Ramos]]></dc:creator>
            <pubDate>Sat, 27 Mar 2021 23:35:03 GMT</pubDate>
            <atom:updated>2021-03-29T18:50:00.339Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5rXejhcKLorK7JiXnQH-tg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@homajob?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Scott Graham</a> on <a href="https://unsplash.com/s/photos/analysis?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>In this article, we are going to analyze an E-commerce dataset that contains transactions occurring over two years (2010 and 2011). The dataset was picked from <a href="https://www.kaggle.com/carrie1/ecommerce-data">Kaggle</a> in excel format and is related to a UK-based company that operates on an E-commerce market.</p><p>Using Python 3 and Jupyter Notebook, we will perform some tasks to prepare our dataset so that we can perform exploration and analysis of the sales data of the fictitious company at a business level. The task to prepare the dataset will be:</p><pre>1. Rename columns labels to lowercase<br>2. Rename text from column &quot;description&quot; to lower case<br>3. Set data types correctly<br>4. Handle Missing values<br>5. Check Duplicates values<br>6. Search for Outliers</pre><p><strong>Let’s get started</strong></p><p>We need to import the relevant libraries that would be useful for our analysis, then, load the data into Pandas. We can do this with a few Python commands:import pandas as pd, import numpy as np, pd.read_csv()</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a_DcPR9lPUPzd9xpx_82aw.png" /><figcaption>Importing relevant libraries and loading the data</figcaption></figure><blockquote>Note: Make sure you have your dataset in the same folder as you are running the Python script. If you have it stored elsewhere, you will need to change the read_csv parameter to point to the file’s location.</blockquote><p><strong>Knowing our data</strong></p><p>Let’s inspect our data. To do that, we can use .head() and .tail() functions. It gives us the <em>n </em>first rows and the last<em> n </em>rows of the data respectively. The default number of rows displayed by <em>.head()</em> and .tail()is five, but we can specify any number of rows as an argument. In this case, we want to get the first 15 rows and the last 10 rows. We’ll see the following result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*JmrtMmlDeAllrxVNIIV32A.png" /><figcaption>First 15 rows</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*Nhmtz5tEzvPSLheGFLlAHQ.png" /><figcaption>Last 10 rows</figcaption></figure><p>Each row in the dataset corresponds to an order made by a customer. We have information about:</p><pre><strong>Product:</strong><br><em>1.StockCode - C</em>ode assigned to each distinct product; <br><em>2.Description - P</em>roduct name; <br><em>3.Quantity </em>- The quantities of each product (item) per transaction; 4.<em>UnitPrice - P</em>roduct price per unit.</pre><pre><strong>Customer:</strong><br><em>1.Customer ID</em> - Number assigned to each customer <br><em>2.Country</em> - Country where each customer resides.</pre><pre><strong>Others features: </strong><br>1.InvoiceNo- Number assigned to each transaction; <br><em>2.InvoiceDate- T</em>he day and time when each transaction was generated.</pre><p>First, for better readability we will rename the columns and replace text within the <em>Description</em> column from uppercase to lowercase:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1007/1*UhIHrifHBEDAqosK_V64EA.png" /><figcaption>Renaming the columns and replacing text</figcaption></figure><p>The code displays the new result below and after that, we make a copy of the dataset assigning data to the new variable:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*vmgDN1pOK0MnmrjwRIfOKw.png" /><figcaption>Output after renaming column header and description column value</figcaption></figure><p><strong>Understanding the data</strong></p><p>We use .info() function to identify the data types and some basic information on the content of the <em>DataFrame</em>. df.info() should return a list of all the columns in our dataset (8 columns in total), <em>541909</em> rows, the number of missing values, as we see in the table below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*q3yfAehx4T6NiKoUtpcVSw.png" /><figcaption>Basic information</figcaption></figure><p>The dataset contains over 540,000 transactions made by the customers, five of our column have the data type object, two are floatand one is integer. However, we have a column candidate for datetime conversion. Take a look at the i<em>nvoice_date </em>column. Pandas assign object to the column but it should be a datetime type.</p><p>Comparing the output after renaming the columns and comparing it with the DataFrame info seen above we can see an inconsistency in the data type. At first glance,<em> </em>the <em>invoice_no </em>column seems to be number type, but it assigned with a stringtype, so there must be something with this variable that will need forward attention.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*9nvwJNW9-kjJjAlyLMBoEQ.png" /></figure><p>Upon taking a closer look, even though the first 3 columns are objects, we can see from the data that only the <em>description</em> column have mixed types. <br>The table also informs us that the d<em>escription</em> column and c<em>ustomer_id </em>have only 540,455 and 406,829 <em>non-null</em> values respectively. This means that we have missing values since we have 541,909 entries in total.</p><p>Now that we know our dataset, our next move will be preparing our data by cleaning it up.</p><p><strong>Data preparation/Data Cleaning</strong></p><ul><li><strong>Changing data types</strong></li></ul><p>Knowing the data type of our dataset helps us to make better valuation and improves performance by ensuring that the data is stored correctly. We saw above that,<em> customer_id, invoice_no, stock_no</em> are unique identifier for each transaction and<em> invoice_date</em> column is stored with an incorrect data type. c<em>ustomer_id</em> is stored as a float number, <em>Invoice_date</em> column is a date stored as objectformat.</p><p>We use<em> </em><em>pd.to_datetime() </em>to convert the i<em>nvoice_date </em>column from<em> </em>objectto<em> </em><em>datetime format and </em>.astype() function to convert the c<em>ustomer_id</em>, and we get this result<em>:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*Uk2WOiND34mMVB96-zxxEg.png" /><figcaption>ValueError</figcaption></figure><p>The output means that we cannot modify a data type that has missing values. <em>invoice_date</em> was set to datetime correctly because it has no missing values as we saw previously but relatively to <em>customer_id</em>, we get a <em>ValueError</em> because we have missing values. To convert the <em>customer_id</em>, we must first handle the missing values.</p><ul><li><strong><em>Dealing with missing values</em></strong></li></ul><p>Missing values (or missing data a.k.a NaN) is a common problem in data science projects which can have a significant effect on conclusions as it can lead to incorrect analysis. This could be because it was filled out unproperly, or the data was not available or could be a computing error.</p><p>Inspecting our <em>dataset </em>above with info() we could see the total of <em>non-null</em> values at each column. Now, we can take a closer look at the data to detect missing values using isnull() and sum() function at the same time.</p><p>The isnull() function returns false if we do not have missing values and true<em> </em>otherwise. The sum() function returns the sum of those missing values in each column. We could also use .sort_values() function with ascending=False parameter to sort the output in descending order as we can see below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*lGL--GQ8txtoLbQROQBeTQ.png" /><figcaption>Missing values</figcaption></figure><p>This output shows us more clearly that c<em>ustomer_id </em>and <em>description</em> column has 135,080 and 1454 missing values respectively.</p><p>We can check out the rows with those missing values below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*7B-txK7x93fzrqZ3CKS2FA.png" /><figcaption>10 first rows with missing values</figcaption></figure><p>Let’s first check out the nulls values we have in<em> the description </em>column:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*Z9M4bucSUyaWvRAhJ3SYMA.png" /></figure><p>Since we saw previously that the <em>description</em> column has mixed values types of string and float , we could confirm that the floats values presented in the column are NaN, so to deal with this column, we could just make an imputation with ‘<em>unknow_item’</em>.</p><p>However, the table also shows us that the NaN missing values in the <em>description </em>column which matches with the NaN in the <em>customer_id </em>column<em> </em>and since the <em>customer_id </em>column is a random system-generated value and we cannot replace them with another value, it doesn&#39;t matter if we impute the <em>description</em> column with “unknown item” because all of the NaN rows will be dropped using data=data.drop(columns=[&#39;customer_id&#39;)letting us with 406,829 rows.</p><blockquote>Note: In some cases, we could opt to drop columns instead of deleting rows. To do that we just would needed to use .dropna() again and provide the axis=1 parameter, however in this particular case we can’t remove the columns because they are relevant for our analysis that will take place forward.</blockquote><p>Now that we have the missing values removed, the <em>customer_id</em> column was successfully converted to string type :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*zdr5RUkoNM7QmcrRH3YPKw.png" /></figure><p>Another common issue is duplicate data.</p><ul><li><strong>Checking Duplicates</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*IuQMFxjIpJCpV1ZUz5QDhw.png" /><figcaption>Rows with only duplicates data</figcaption></figure><p>In total the dataset has 5225 duplicate values. We can delete them using (drop_duplicates(keep=False, inplace=True) leaving us with 396,767 entries. With the data cleaned of duplicates and null values, we can start searching for patterns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*UuD1tW6Iep5Cde1b9VZH7g.png" /></figure><ul><li><strong>Searching for patterns</strong></li></ul><p>The next analysis is to perform descriptive summary data on numeric variables. Using describe() method, we get the following result and concerns:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/238/1*tGU1wpWgmr8PUpgMwePfjg.png" /></figure><pre>1. Why <em>invoice_no</em> is not considered a numeric value as it is a column with numbers?</pre><pre>2. Why the <em>quantity column</em> has negative values and extremely positive and negative values wich indicates outliers</pre><pre>3. What about <em>unit_price</em>, How the minimum values are zero? it indicate free items to customers?<br></pre><p>Let’s take a look at those features one by one:</p><p>Using some methods we found that the<em> invoice_no </em>column has text (starting by letter C) corresponding to 8844 rows, and numbers that correspond to 397924, as shown below. how can we explain this?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/1*dic260M6wSYMqqN3iX7hDA.png" /><figcaption>Entries starting with the letter C</figcaption></figure><p>The negative values seem that corresponds to each <em>invoice_no</em> that has been cancelled. We verify this by defining a command to grab only the negative values (see the project on my GitHub <a href="https://github.com/kueilaramos/ecommerce-project">repo</a>). This is explained by the negative values in the <em>quantity </em>column<em>. </em>As a result, it returns us a DataFrame where the <em>invoice_no</em> started by letter C, as shown in the table below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*QriibL6WyHNKEOVeUDozdg.png" /></figure><p><strong>2. Graphical visualization of the numeric data (quantity and unit_price)</strong></p><p>Looking at the histogram below, we can see that the majority of the quantity data is centred in the middle and the unit price range between 0 to 40000.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*MCbj4CwrU1aFZr696jFxKw.png" /><figcaption>Quantity vs unit_price graphical representation</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/238/1*tGU1wpWgmr8PUpgMwePfjg.png" /></figure><p>Out of the 396767 rows, we observe that the maximum and minimum value are respectively 80995 and -80995. The Interquartile range analysis tells us that most of the values lie between 2 and 12. Values greater than 12 introduces us to Outliers. To know more about outliers we have to Get relevant percentiles and see their distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/417/1*IZmCKA3dwgEP1JU3LKuO4Q.png" /></figure><p>Now that we find the upper fence and lower fence, by adding some code we can plot all the data above the upper fence and below the lower fence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*hOyk9t8HeE0PWUVbtFjwqQ.png" /></figure><p>Filter out the outlier data and print only the potential data, we obtain the following result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*4SulCdTJFdWzXOkhJzNoSQ.png" /></figure><p>Now, the result shows an extreme outlier in the unit_price which corresponds to a transaction that has a unit_price of 38970:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*LZ0ghOC5TBFnUkBLOKQe7g.png" /></figure><p>To deal with that, we drop the outlier. After that, we go again to check the distribution of the price and we found more outliers, here is the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*bJB39foaNTnKQxjx-ebKfQ.png" /></figure><p>An outlier is a value or an entire observation that lies well outside of the norm. By looking at the histogram and box plot above, now we can see that the maximum and minimum value of the <em>unit_price </em>column are respectively 0.00 and 8142.</p><p>For this particular example, <em>unit_price</em> is extremely above 75 percentile and those values seem legitimate but it is way beyond what the prices average of the products are. However, we decide to keep outliers.</p><p>After this statistical analysis, in the next section, we will make an exploratory analysis and answer a couple of business-focused questions.</p><p><strong>EXPLORATORY DATA ANALYSIS</strong></p><ul><li><strong>Categorical variables</strong></li></ul><p>Within pandas, to get the non-numerical features we apply describe() function and we specify include=&#39;object&#39; to the function which returns the number of values (count), unique values unique), the most frequent value (top) and the frequency (freq) in the dataset.</p><blockquote>Note: using numpy object data type <em>describe(include=np.object)</em> will give us the same result.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*nrzQe9cG18CPLCgBgAd-8w.png" /></figure><p>For a quick interpretation, the product most sold was ‘<em>regency cakestand 3 tier’</em>. We have 37 countries in total. The United Kingdom is the top country and the most frequent country with a higher number of orders (20660) which corresponds to approx. 89% of the dataset.</p><h3>Answering business questions</h3><pre><strong>1. What&#39;s are the TOP 5 countries with the highest number of orders?</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HXojoaaHvVONAaVbhQF-ug.png" /></figure><p>The company receives the highest number of orders from customers in the United Kingdom (since it is a UK-based company). Therefore, the TOP 5 countries that place the highest number of orders are the United Kingdom, Germany, France, EIRE and Spain.</p><pre><strong>2. What&#39;s are the TOP 5 countries with highest number of sales?</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*UNW0gLZ9fAnku_E9oV7AUA.png" /></figure><p>As the company receives the highest number of orders from customers in the United Kingdom (since it is a UK-based company), customers in the United Kingdom spend the most on their purchases. Therefore, the table result above give us the TOP 5 countries that sold the most are United Kingdom, Germany, France, EIRE, Switzerland.</p><pre><strong>3. What was the Total sales per year?</strong></pre><p>The transactions occurred between two periods (2010 and 2011). Globally, in total, the sales were 3,432.593 in 2010 and 4,782.446 in 2011.</p><p>However, by looking at a specific country, for example, the United Kingdom the result is shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*ICb6IPVapM5mDtLf8fQRPw.png" /></figure><pre><strong>4. How many different orders made by the customers in United Kingdom?</strong></pre><p>We see that the dataset is largely dominated by orders made from the United Kingdom. The DataFrame contains 330.908 entries to simplify we could ask what is the number of customers and products in these entries?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/158/1*50aol5-38uIx7_c_hLBFTg.png" /></figure><p>It can be seen that the data concern 3.858 different customers and that they bought 3.643 different products. The total number of transactions carried out was above 18.427 orders. see the table below for years separately.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*18LdzpQ0DN14vlOIUX-D2g.png" /></figure><pre><strong>5.What was the best month for sales in United Kingdom? How much was earned that month?</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*xdQoZaARRKMXbbMKfOtIQw.png" /></figure><p>The best month for sales in 2010 was December. The best month for sales in 2011 was November. You can also see the graphical representation below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*GkMbQxDZ0BA6IhPL9E1WVg.png" /></figure><pre><strong>6.In 2011, <em>How many orders was made per hour? </em>How many orders was made per day?</strong></pre><p>From the graphical representation below we can conclude that most orders occur at 12 hours, and usually, customers make more purchases on Thursday.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*_trJQDTFmkS5HtwaQAghDg.png" /></figure><pre><strong>7. How many transactions was made and which corresponds to orders canceled<em>?</em></strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*YOXhBsllpzdmFXuqqUVS3Q.png" /></figure><p>This result shows us the existence of frequent customers that buy a large number of items at each order. The existence of entries with the prefix C for the <em>invoice_no</em> column indicate transactions that have been cancelled. And for that client number 12924, only 1 transaction was cancelled.</p><p><strong>Summary</strong></p><p>This article was to demonstrate the steps I adopted on the analysis of an e-commerce dataset. First of all, I performed some tasks that include: drop NaN values from DataFrame; removing rows based on a condition; change the type of columns (to_datetime, astype), drop duplicate data and also handle outliers for statistical purpose. Then the article moves to the Exploration data Analysis where we explore questions at the business level related to our data.</p><p><strong>Reference</strong></p><ul><li><a href="https://www.kaggle.com/carrie1/ecommerce-data">E-Commerce Data</a></li><li><a href="https://github.com/kueilaramos/ecommerce-project">kueilaramos/ecommerce-project</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=374f038dcbc2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Economics to Data Science]]></title>
            <link>https://kueilaramos.medium.com/from-economics-to-data-science-582792f1bb28?source=rss-99cb0af6393e------2</link>
            <guid isPermaLink="false">https://medium.com/p/582792f1bb28</guid>
            <category><![CDATA[economics]]></category>
            <category><![CDATA[start-over]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[finance-and-banking]]></category>
            <category><![CDATA[business-analysis]]></category>
            <dc:creator><![CDATA[Kueila Ramos]]></dc:creator>
            <pubDate>Sun, 20 Sep 2020 23:59:04 GMT</pubDate>
            <atom:updated>2020-09-20T23:59:04.598Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BXpZcITKj2anh261djW7jw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@ktabori?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Krisztian Tabori</a> on <a href="https://unsplash.com/s/photos/pedra-lume?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h4>Hi everyone, my name is Kueila Cristina and<strong> </strong>I am going<strong> </strong>to make a quick intro about myself and my career path so far and my growing interest in data science.</h4><p>Born in Cape Verde in 1992, where I finished my 12th grade on Science and Technology area in Sal island, then I wanted to try something new and gain new perspectives and opportunities, so I moved to Portugal in 2011 to get my degree. In this journey, I have always brought homesickness, carried by the sense of responsibility and learning that the new life would bring me, the same fundamental aspects that have made me grow as a person.</p><p>I chose to graduate in Business Science because it combines two areas that I always liked: math and business since I was 12 years old, I helped my mom in her groceries store, managing sales and stock, it was right there that I gain interest in the business area. So I chose to get my degree in Business Science in <em>Escola Superior de Tecnologias e Gestão de Felgueiras.</em></p><p>After getting my degree in 2015, I was excited about the economy and the world of finance and banking, so I decided to get my Masters in Economics, however, due to financial difficulties, I stopped studying for two years to work and get financial conditions to continue my studies. I worked as a waitress, and it was a very positive and enriching experience as it helped me work on my teamwork, communication and work ethic skills.</p><p>In 2017, I finally started my Master degree in economics, and it was concluded in October 2019. During this time<strong> </strong>I was trying to find my first job opportunity so I could learn and gain experience<strong>, </strong>but with no luck.</p><p>Fortunately, I joined my friend <a href="https://medium.com/@caiogmartins">Caio Martins</a> who was freelancing with projects, which dwelled with some techniques/tools like excel to solve financial, economics and marketing tasks until February 2020 which, unfortunately, due to COVID we didn’t have more projects so we have to search for alternatives.</p><p>I felt that I needed to gather what I learned in my academic path and on freelancing and create a new opportunity for myself. During this period of reflection and exploring, I gained a strong interest in statistical data analysis, but I wanted to do something related to Python.</p><p>Python is a programming language used for web development, Data Science and Machine learning. It is well known by its versatility, portability and library support. By those advantages and its community feedback, from a statistical data analysis point of view I decided to use Python as my tool for data analysis.</p><p>So, for starters, I did not know how to code, I mean I dabbled with some HTML but not something of much value. I was really out of my comfort zone. But I kept pushing with resources found on P<a href="https://docs.python.org/3/tutorial/"><em>ython tutorial</em></a>, <a href="https://www.dataschool.io/"><em>Dataschool</em></a>, <a href="https://www.geeksforgeeks.org/python-programming-language/?ref=leftbar">G<em>eeksforgeeks</em></a><em>, and </em><a href="https://www.udemy.com/course/the-data-science-course-complete-data-science-bootcamp/"><em>Udemy Courses</em></a><em> </em>which<em> </em>dive into concepts from the basics to more in-depth Data Science but focused on data analysis and machine learning.</p><p>Even though with no coding experience and the need for a breath of fresh air on my career path options, I decided to shift to Data Science by self-learning. It has been a challenging experiencing, but the fact that by using data science to solve problems, analyze data by my own it has been a very rewarding experience which validates my decision to have chosen this path.</p><p>The feeling of challenging myself, keep pushing and for your goals and being resilient has made me grow as a person and increased my will of getting of my comfort zone.</p><p>Talking about getting out of my comfort zone, I also decided to share my experience through Medium. Since I have a lot to learn in this field I wanted to share this experience so that people that might be going through the same situation, there are still options and its never too late and if you keep pushing yourself the feeling of pride is very rewarding.</p><p>By that, I will be posting blog posts of my projects that I been experimenting with new tools, new techniques and the experience I’ve been gaining by coding.</p><p>As for a starting point, my main topics of study will be focused on marketing and finance, specifically on customer retention and sales analysis. My goal is to understand Data Science, Machine learning in-depth and combine with my Economics background.</p><p>As for my <strong><em>“</em></strong><a href="https://medium.com/@KueilaRamos/getting-started-with-data-science-by-cleaning-up-data-f16dfeab0d32"><strong><em>Getting started with Data Science by cleaning up data sets</em></strong></a><strong><em>”,</em></strong> my goal was to use a dataset and show techniques use to clean up the data.</p><p>Feel free to comment and leave feedback, since this still pretty fresh and I have a lot to learn. For that, here’s my LinkedIn profile link. Thank you all for your time and I see you soon.</p><h4>References</h4><p><a href="https://medium.com/@KueilaRamos/getting-started-with-data-science-by-cleaning-up-data-f16dfeab0d32">Getting started with Data Science by cleaning up data</a></p><p><a href="https://www.python.org/about/apps/">https://www.python.org/about/apps/</a></p><p><a href="https://medium.com/@mindfiresolutions.usa/advantages-and-disadvantages-of-python-programming-language-fd0b394f2121">https://medium.com/@mindfiresolutions.usa/advantages-and-disadvantages-of-python-programming-language-fd0b394f2121</a></p><p><a href="https://docs.python.org/3/tutorial/">https://docs.python.org/3/tutorial/</a></p><p><a href="https://www.w3resource.com/python/python-tutorial.php">https://www.w3resource.com/python/python-tutorial.php</a></p><p><a href="https://www.geeksforgeeks.org/python-programming-language/?ref=leftbar">Python Programming Language - GeeksforGeeks</a></p><p><a href="https://www.dataschool.io/">www.dataschool.io</a></p><p><a href="https://www.udemy.com/course/the-data-science-course-complete-data-science-bootcamp/">Data Science Training Course: Data Scientist Bootcamp</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=582792f1bb28" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting started with Data Science by cleaning up data]]></title>
            <link>https://medium.com/analytics-vidhya/getting-started-with-data-science-by-cleaning-up-data-f16dfeab0d32?source=rss-99cb0af6393e------2</link>
            <guid isPermaLink="false">https://medium.com/p/f16dfeab0d32</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-cleaning]]></category>
            <category><![CDATA[starting-up]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Kueila Ramos]]></dc:creator>
            <pubDate>Sun, 20 Sep 2020 23:56:04 GMT</pubDate>
            <atom:updated>2020-09-27T14:26:13.572Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UAZ_3teUWXuIt9vB1HZYLw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@campaign_creators?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Campaign Creators</a> on <a href="https://unsplash.com/t/business-work?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h4>Hy everyone, this is my first starting point in the field of Data Science. In this article, I am going to share my experience on a simple data cleaning on Python.</h4><h3><strong>Introduction</strong></h3><p>Whenever we start doing analysis on Python, usually the first step after importing the necessary packages is to load the data into a Pandas DataFrame using for example read_csv method, read_excel, read_table or read_sql depending on the extension of the file. However, in some cases, if we want to work with a small amount of data, it is also helpful to know how DataFrame works.</p><p>For the purpose of this article, I am using <a href="https://jupyter.org/">Jupyter Notebook</a> as Integrated Development Environment (IDE) and I am going to use sales data to perform data cleaning, but before this, I am quickly going to manually show one common way to create a DataFrame using a list of dictionaries.</p><p><strong>Let´s get started</strong></p><p>To create a table manually, Python´s Pandas packages provide a constructor for DataFrame that consist of pd.Dataframe()<em> </em>method<em>.</em> (pdis used as an alias for that Pandas library instance).</p><p>Let’s use a list of dictionaries from the Pandas library to have a look at its functionality:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/981/1*QRE22nq2eA7fwKPPfApdSw.png" /></figure><p>Each key (<em>Order ID, product, quantity ordered</em>…) corresponds to a column name and values for data as lists. As you can see above, I defined a dictionary list and stored the variable name as data and then I use the constructer to create the DataFrame and assign it to sales and after we printed, it gives us a representation of the <em>dataset</em>. The <em>dataset</em> was modified and it is an extract from a much larger dataset, to show you one of the common issues in Data Science projects that may affect our analysis: inconsistent column names, capitalization, missing data, incorrect data types etc.</p><p>Now, Taking the original data from <a href="https://github.com/KeithGalli/Pandas-Data-Science-Tasks/tree/master/SalesAnalysis/Sales_Data">Keith Galli´s Github repository</a> (it contains files separately from Jan to December 2019), I want to do the following:</p><ul><li>Rename the variables columns;</li><li>Handle missing values;</li><li>Handle data types</li></ul><p>By importing the full table into the <em>DataFrame </em>with one line of code using the read_csv<strong><em> </em></strong>command.<strong><em> </em></strong>To perform identical analysis that Keith has done on his repository, but with some adaptation, I started by analysing <em>sales_April_2019</em> once the CSV file was loaded. The first five rows of the table before any operations is attached below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*AK5VGHyO5Ncza7kPqFrIMA.png" /></figure><p>At first glance, We can see one problem: M<strong>issing values</strong> (the DataFrame has the second entry as NaN which means the value is not available). To facilitate the analysis I firstly rename the variables columns:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*kAhgn3RU9wZqtpG9mLDtQQ.png" /></figure><p>To inspect the data, we can use the following code to get a sense of how the <em>dataset </em>looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*4sfw9ICr76zy7ooQXiGz5w.png" /></figure><p>The data consists of 18383 rows and 6 columns. Incorrect column type was also identified as a problem, whereas all variables types are object which is wrong because we have numerical and categorical variables. So before moving forward, we have to solve those problems.</p><p>From here, firstly we are solving the missing values and then check the data types that are not set correctly. So the total of missing values for each feature is 59 and in total, we have 354 missing values as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*c7D3rWwlilbP0xFpCtG_Kg.png" /></figure><p>Now that we’ve summarized the number of missing values we have 3 options:</p><ol><li>We can drop the rows or columns if they are not relevant for your analysis;</li><li>We can replace the missing values for a more convenient value;</li><li>We can ignore them</li></ol><p>Ignoring the missing values is not always a good idea because at some point you will have to deal with them.</p><p>For this particular case, as each column has the same amount of missing values and they are not a very high number, so we can drop them. Now, the dimension of the data frame is 18324:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*oSxyAThw155gutIcJfWsDA.png" /></figure><p>After that, we proceed to handle incorrect column type. Before moving on we will make a copy of the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*vXZ6QNQIBS6TtyY1gDI9tQ.png" /></figure><p>Pandas recognized the NaN<em> or </em><em>np.nan</em> as a missing value, but what if our feature is expected to be numeric, but there is a categorical type for example? Technically this is also a missing value.</p><p>‘q<em>uantity_ordered</em>’, and ‘p<em>rice_each</em>’ were expected to be numeric value and <em>‘order_date’ </em>to be a date type<em>.</em> When we were trying to modify the type of the columns using the apply() function, a <em>ValueError</em> was displayed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d-Tj37iMUtVEaF77zDhI2A.png" /></figure><p>Using the code below, we can see that we have a bunch of lines identified as categorical values that didn’t allow us to modify the data type:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*w97Jcau8UCIUEokOPiOwNA.png" /></figure><p>So, to solve this problem, we can apply the np.where() function to replace the categorical values with np.nan<strong> </strong>(i.e, missing value). Doing that, we can identify more 35 missing values in each column, after that, we will drop all of those values:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/981/1*FaeQC5jDjDfrfrovZ8gR4w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*yGSj1ZxYt-pm6diA9r5H-A.png" /></figure><p>With the missing values dropped, we could now modify the data types:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*fqY5lsbvIQKxRXTgQUz9Qw.png" /></figure><p>The pd.to_numeric()<strong><em> </em></strong>and pd.to_datetime() will process the data and create a <em>float64</em> column by default as we can see on the outcome bellow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*fdyLE0Q0lJp2y_c0Ew0hNA.png" /></figure><p>Finally, we transform float <em>quantity_ordered</em> column to an integer by using this line of code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*XZGjOhupzGWTSTIwyHeUWA.png" /></figure><p><strong>Conclusion:</strong></p><p>This study shows me that there are a lot of different approaches to solve one problem. I am a beginner in the field of data science, who is trying to find his way to go from doing simple analysis to more complex ones forward. This particular exercise makes me feel that I have a lot to learn and I am really enjoying it.</p><p>So, you can find the git repository <em>Jupyter Notebook</em> of this article h<a href="https://github.com/kueilaramos/Getting-started-with-Data-Science-by-cleaning-up-data-sets">ere</a>. Thank you for reading this blog and the support and I have more on the way, just stay tuned.</p><h4>References</h4><ul><li><a href="https://jupyter.org/">Project Jupyter</a></li><li><a href="https://github.com/KeithGalli">KeithGalli - Overview</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f16dfeab0d32" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/getting-started-with-data-science-by-cleaning-up-data-f16dfeab0d32">Getting started with Data Science by cleaning up data</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>