<?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 Caleb Chijindu Ugorji on Medium]]></title>
        <description><![CDATA[Stories by Caleb Chijindu Ugorji on Medium]]></description>
        <link>https://medium.com/@ugorjicalebchijindu?source=rss-b330e45b2799------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*3YoKT9w5LjB1sj3aXNuXCQ.jpeg</url>
            <title>Stories by Caleb Chijindu Ugorji on Medium</title>
            <link>https://medium.com/@ugorjicalebchijindu?source=rss-b330e45b2799------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 11:25:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ugorjicalebchijindu/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[Discover the Easiest Way to Measure the Effectiveness of Your Programs, Projects, or Training!]]></title>
            <link>https://medium.com/@ugorjicalebchijindu/discover-the-easiest-way-to-measure-the-effectiveness-of-your-programs-projects-or-training-7435865fa288?source=rss-b330e45b2799------2</link>
            <guid isPermaLink="false">https://medium.com/p/7435865fa288</guid>
            <dc:creator><![CDATA[Caleb Chijindu Ugorji]]></dc:creator>
            <pubDate>Wed, 21 Feb 2024 00:55:28 GMT</pubDate>
            <atom:updated>2024-02-21T00:55:28.496Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/450/0*7t3Ix4OfQnPhA8pA.jpg" /></figure><p>It is crucial to evaluate the effectiveness of a program, activity, or training to determine its progress and identify areas for improvement.</p><p>One common way to check if progress was made towards the goal of any program is by conducting a pre and post-test. The pre-test evaluates the knowledge of the participants before the program to form a baseline while the post-test evaluates the knowledge of the participants after the program.</p><p>One common method to derive insights and draw conclusions from this exercise is to conduct a paired-sample t-test analysis. This test compares the average scores of participants at the program&#39;s start and end and determines whether there was a significant difference between them.</p><p>In reporting a paired sample t-test, here are some important parameters to include</p><ol><li>The degree of freedom: which is usually one minus the sample size.</li><li>The mean difference: the average of the paired observations’ differences.</li><li>The standard deviation: indicates how spread out the values in a dataset are from the mean.</li><li>The t-statistic: a measure that quantifies the difference between the means of paired observations while accounting for the variability within the pairs. It is calculated by dividing the mean difference between paired observations by the standard error of the differences. Typically, the higher the t-statistic the higher the chance of getting a significant difference in the observed means.</li><li>The P-value: the p-value is a statistical measure that indicates the probability of obtaining observed results, or more extreme results, under the assumption that the null hypothesis is true. In paired sample t-test analysis, the null hypothesis is that the observed means are the same i.e. there is no difference between the pre-test mean score and the post-test mean score. So a small p-value shows that the chances of upholding this null hypothesis is small hence it is rejected and the alternative hypothesis which is that there is a difference between the observed means is upheld. Typically, a significance level (e.g., 0.05) is chosen, and if the p-value is less than or equal to this threshold, the results are considered statistically significant.</li></ol><p>Recently, I used this method to evaluate the progress of a sports training camp. The pre and post-test scores of the players on various sports tests were provided by the training director.</p><p>Here is a snapshot of the data</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*flqmqtAB__5zW68tXyu7aw.jpeg" /></figure><p>Many statistical packages can be used to carry out a paired sample t-test. Check out this video on how to do a paired sample t-test on SPSS — <a href="https://youtu.be/u3u2Wbcn-P0?si=5I5zzE3EIQxtG4Kb">https://youtu.be/u3u2Wbcn-P0?si=5I5zzE3EIQxtG4Kb</a></p><p>This is a snapshot of the output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*wTTKLmH0CaOjYgJlxZMEAQ.jpeg" /></figure><p>This result showed a statistically significant difference in the pre and post-test mean scores of the two tests. The sign (+ or -) in the T value shows the direction of the change. The second test with the negative T value means that the players score higher in the post-test than in the pre-test. The Mean in the table is the average of the score difference.</p><p>This approach applies to analyzing public health programs and campaigns that seek to see an increase in a particular indicator after carrying out some activities.</p><p>It is crucial to keep in mind that the paired sample t-test relies on the assumption that the differences between paired observations follow a normal distribution. If this assumption is significantly violated, the results of the test may be less reliable. Additionally, the paired sample t-test assesses the mean difference, which can be influenced by outliers and extreme values. Therefore, the test might be compromised in the presence of such values.</p><p>Thanks for reading.</p><p>Kindly follow me for more tips.</p><p>Bye for now!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7435865fa288" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing an SQL query to answer this question took me back to the basics: The Order of SQL Query…]]></title>
            <link>https://medium.com/@ugorjicalebchijindu/writing-an-sql-query-to-answer-this-question-took-me-back-to-the-basics-the-order-of-sql-query-754b1da72585?source=rss-b330e45b2799------2</link>
            <guid isPermaLink="false">https://medium.com/p/754b1da72585</guid>
            <dc:creator><![CDATA[Caleb Chijindu Ugorji]]></dc:creator>
            <pubDate>Tue, 23 Jan 2024 18:05:05 GMT</pubDate>
            <atom:updated>2024-01-23T18:05:05.428Z</atom:updated>
            <content:encoded><![CDATA[<h3>Writing an SQL query to answer this question took me back to the basics: The Order of SQL Query Execution</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*eYaIUrd9nTa-IebV77dWAg.jpeg" /><figcaption>Query output visualized on Tableau</figcaption></figure><p>In this article, I briefly explained the order in which SQL queries are executed. I encountered this concept during my beginner days as a data analyst in the Udacity SQL for data analysis course. However, I never paid close attention to it.</p><p>You don’t necessarily need to know how SQL queries are executed to be able to write them but the knowledge comes in handy when you are trying to decipher why a query you wrote is giving you a wrong output.</p><p>In my case, I was trying to write a query that calculates the percentage contribution of each customer cohort to the total sales for each year. The customers have already been grouped into cohorts based on the year of their acquisition as you can see in the subquery in the FROM clause.</p><p>Below is the first query I wrote.</p><pre>SELECT acquisition_year, <br>  CASE WHEN sales_2011 = 0 THEN 0 ELSE ROUND((sales_2011 * 100.0) / NULLIF(sum(sales_2011), 0),2) <br>        END AS percentage_sales_2011,<br>  CASE WHEN sales_2012 = 0 THEN 0 ELSE ROUND((sales_2012 * 100.0) / NULLIF(sum(sales_2012), 0),2) <br>        END AS percentage_sales_2012,<br>  CASE WHEN sales_2013 = 0 THEN 0 ELSE ROUND((sales_2013 * 100.0) / NULLIF(sum(sales_2013), 0),2) <br>        END AS percentage_sales_2013,<br>  CASE WHEN sales_2014 = 0 THEN 0 ELSE ROUND((sales_2014 * 100.0) / NULLIF(sum(sales_2014), 0),2) <br>        END AS percentage_sales_2014 <br>FROM (<br>       WITH CustomerAcquisitionYear AS (<br>  SELECT<br>    customer_id,<br>    EXTRACT(YEAR FROM MIN(order_date)) AS acquisition_year<br>  FROM<br>    tsql.global_superstore<br>  GROUP BY<br>    customer_id<br>)<br><br>SELECT<br>  cay.acquisition_year,<br>  SUM(CASE WHEN EXTRACT(YEAR FROM gs.order_date)::int = 2011 THEN gs.sales ELSE 0 END) AS sales_2011,<br>  SUM(CASE WHEN EXTRACT(YEAR FROM gs.order_date)::int = 2012 THEN gs.sales ELSE 0 END) AS sales_2012,<br>  SUM(CASE WHEN EXTRACT(YEAR FROM gs.order_date)::int = 2013 THEN gs.sales ELSE 0 END) AS sales_2013,<br>  SUM(CASE WHEN EXTRACT(YEAR FROM gs.order_date)::int = 2014 THEN gs.sales ELSE 0 END) AS sales_2014<br>FROM<br>  tsql.global_superstore gs<br>JOIN<br>  CustomerAcquisitionYear cay<br>ON<br>  cay.customer_id = gs.customer_id<br>WHERE<br>  EXTRACT(YEAR FROM gs.order_date) BETWEEN 2011 AND 2014<br>GROUP BY<br>  cay.acquisition_year<br>ORDER BY<br>  cay.acquisition_year  <br>) A<br>group by acquisition_year, sales_2011, sales_2012, sales_2013, sales_2014</pre><p>The output of this query is a table of the percentage contribution of the customer cohorts to the total sales across the years but all the cohorts had a 100 percent contribution.</p><p>To decipher what was going on, I had to pause for some minutes to think through how SQL queries were executed.</p><p>In the order of execution of SQL queries, the GROUP BY clause is executed before the SELECT clauses therefore the sales and the sum of sales i.e the total sales become the same thing when the data is grouped by the acquisition year hence the 100 percent contribution of all the cohorts.</p><p>To resolve this I made the sum a Windows function by introducing the OVER() function. This performs a window sum of the sales for each year. Since the window is not specified by the PARTITION BY keyword, it sums the whole observation(rows) for each year therefore giving the total sale for each year.</p><p>Below is the query</p><pre>SELECT acquisition_year, <br>  CASE WHEN sales_2011 = 0 THEN 0 ELSE ROUND((sales_2011 * 100.0) / NULLIF(sum(sales_2011) over(), 0),2) <br>        END AS percentage_sales_2011,<br>  CASE WHEN sales_2012 = 0 THEN 0 ELSE ROUND((sales_2012 * 100.0) / NULLIF(sum(sales_2012) over(), 0),2) <br>        END AS percentage_sales_2012,<br>  CASE WHEN sales_2013 = 0 THEN 0 ELSE ROUND((sales_2013 * 100.0) / NULLIF(sum(sales_2013) over(), 0),2) <br>        END AS percentage_sales_2013,<br>  CASE WHEN sales_2014 = 0 THEN 0 ELSE ROUND((sales_2014 * 100.0) / NULLIF(sum(sales_2014) over(), 0),2) <br>        END AS percentage_sales_2014 <br>FROM (<br>       WITH CustomerAcquisitionYear AS (<br>  SELECT<br>    customer_id,<br>    EXTRACT(YEAR FROM MIN(order_date)) AS acquisition_year<br>  FROM<br>    tsql.global_superstore<br>  GROUP BY<br>    customer_id<br>)<br><br>SELECT<br>  cay.acquisition_year,<br>  SUM(CASE WHEN EXTRACT(YEAR FROM gs.order_date)::int = 2011 THEN gs.sales ELSE 0 END) AS sales_2011,<br>  SUM(CASE WHEN EXTRACT(YEAR FROM gs.order_date)::int = 2012 THEN gs.sales ELSE 0 END) AS sales_2012,<br>  SUM(CASE WHEN EXTRACT(YEAR FROM gs.order_date)::int = 2013 THEN gs.sales ELSE 0 END) AS sales_2013,<br>  SUM(CASE WHEN EXTRACT(YEAR FROM gs.order_date)::int = 2014 THEN gs.sales ELSE 0 END) AS sales_2014<br>FROM<br>  tsql.global_superstore gs<br>JOIN<br>  CustomerAcquisitionYear cay<br>ON<br>  cay.customer_id = gs.customer_id<br>WHERE<br>  EXTRACT(YEAR FROM gs.order_date) BETWEEN 2011 AND 2014<br>GROUP BY<br>  cay.acquisition_year<br>ORDER BY<br>  cay.acquisition_year  <br>) A<br>group by acquisition_year, sales_2011, sales_2012, sales_2013, sales_2014</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*ZfLIqzWvZ8DshD85MyYS0g.jpeg" /><figcaption>Query output</figcaption></figure><p>Here is a chronological order of how SQL query is executed for most database management systems (DBMS)</p><ol><li>FROM clause: The first step involves identifying the tables and views specified in the FROM clause.</li><li>JOIN clause: If the query involves JOIN operations, the data is combined based on the specified join conditions.</li><li>WHERE clause: The WHERE clause filters the rows based on the specified conditions. Rows that do not meet the criteria are excluded.</li><li>GROUP BY clause: If a GROUP BY clause is present, the data is grouped into subsets based on the specified grouping columns.</li><li>HAVING clause: The HAVING clause filters the grouped data based on aggregate conditions.</li><li>SELECT clause: The SELECT clause is applied to the result set, defining which columns to include and potentially performing calculations or transformations.</li><li>ORDER BY clause: If there is an ORDER BY clause, the result set is sorted based on the specified columns and sort order.</li></ol><p>I hope this serves as a refresher to you on basic SQL.</p><p>Follow me on my social media</p><p><a href="https://twitter.com/calebugorji021">Twitter</a></p><p><a href="https://linkedin.com/in/caleb-ugorji">LinkedIn</a></p><p>Thank you for reading and bye for now!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=754b1da72585" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Use Basic Python Methods to Clean Up Difficult Research Data Quickly]]></title>
            <link>https://medium.com/@ugorjicalebchijindu/how-to-use-basic-python-methods-to-clean-up-difficult-research-data-quickly-bb539c9a81c2?source=rss-b330e45b2799------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb539c9a81c2</guid>
            <dc:creator><![CDATA[Caleb Chijindu Ugorji]]></dc:creator>
            <pubDate>Thu, 02 Nov 2023 06:38:49 GMT</pubDate>
            <atom:updated>2023-11-02T08:09:04.869Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/341/1*pYpmX8QutLr7ODxIZPRsvQ.jpeg" /></figure><p>This article is on how I cleaned up research data that was quite tricky to clean and prepared it for analysis with SPSS. The client said the job would take approximately 2 weeks to do but I did it in two nights using Python.</p><p>You don’t have to be a Python guru to know to do this. Just basic Python knowledge, research knowledge and maybe the assistance of chat GPT, if you run into a problem, will suffice.</p><p>We all know that processing data from research questionnaires can be tedious especially when some questions in the questionnaire give room for respondents to type their answers or have questions with more than one answer therefore requiring the respondent to choose more than one option.</p><p>I have broken down the approaches I took into steps in this article to make it easier to understand.</p><ol><li>Dropping columns that are not needed for the analysis: The dataset had 392 rows and 42 columns. The client already told me that there were columns that weren’t needed for her analysis so I was going to drop them. I dropped the columns using the Pandas method df.drop()</li></ol><pre>df.drop([&#39;column_name1&#39;,  &#39;column_name2&#39;,...], axis = 1, inplace = True)</pre><p>2. Renaming the columns: The column names were the questions in the questionnaire so I had to rename them to something easier to type. To rename the columns, I created a dictionary of old and new names and then use the df.rename command to rename them</p><pre>#creating the dictionary<br>rename = <br>{<br>  &#39;old_name&#39;: &#39;new_name&#39;,<br>  &#39;old_name&#39;: &#39;new_name&#39;,<br>...<br>}<br>#Renaming the columns<br>df.rename(columns = rename, inplace = True)</pre><p>3. In-depth assessment of the data: I used simple pandas methods that everybody knows to critically look through the data although I had previously gone through the data in a spreadsheet.</p><p>The frequent Pandas methods I used to assess the datasets were</p><p>A. df.info(): This returns the column index, column name, non-null count of the column and the data type.</p><p>B. df.columns: returns a list of the column names</p><p>C. Column_name.unique(): This returns the unique values in the column</p><p>D. Columm_name.value_counts(): This returns the unique values in the column and their frequency of occurrence.</p><p>E. df.[‘colume_name’].hist(): this plots a histogram of the variable. Note: this method can only be used on columns with numerical data type</p><p>4. Dropping some rows with outliers and null values: After critically assessing the data, I found some rows with outliers that skewed the variables when their histogram was plotted. I informed my client she said I should expunge such observation. Also, observations with null empty cells(null values) in variables that null values weren’t allowed were also dropped.</p><p>Dropping rows with null values</p><pre>#Getting the row index<br>Index1 = df[df[&#39;column_name&#39;].isnull()].index[0]<br><br>#Dropping the row<br>df.drop(index = index1, axis=0, inplace = True)</pre><p>Dropping outliers</p><pre># Getting the row index<br>Index2 = df[df[&#39;column_name&#39;]&gt;100].index[0])<br><br>#Dropping the row<br>df.drop(index = index2, axis = 0, inplace= True)</pre><p>To analyse data in SPSS, the responses need to be coded into numbers. I used four approaches to do this depending on the kind of data in the variable</p><p><strong>Approach One</strong>: For variables with categorical data that had few unique values, I created a dictionary to map the values to numbers and then used the df.replace method to replace them</p><pre>#Creating the dictionary<br>category_to_number =<br> {<br>  &#39;option1&#39;: 1,<br>  &#39;option2&#39;: 2,<br>  … <br>}<br>#Replacing the values<br>df[&#39;column_name&#39;] = df[&#39;column_name&#39;].replace(category_to_number)</pre><p><strong>Approach Two</strong>: For variables with categorical data that had many unique values, I used a for loop to capture the values that were options in the questionnaire and then categorized the other values that the respondents typed in as ‘Others’</p><pre>#create an empty list<br>empty = []<br><br>#write a for loop that iterates through the column and assigns a number(1, 2, 3…) to the values in the column and appends it to the empty list<br>for i in df[&#39;colume_name&#39;]:<br>    if i == &#39;option1&#39;:<br>       empty.append(1)<br>    elif i == &#39;option2&#39;:<br>       empty.append(2)<br>    elif i == &#39;option3&#39;:<br>        empty.append(3)<br>    else:<br>        empty.append(4)<br>#check by printing the list        <br>print(empty)<br><br>#Replace values the column with the list<br>df[&#39;column_name&#39;] = empty</pre><p><strong>Approach Three</strong>: For variables with numerical data that I had to group into intervals (I.e 0–9, 10–19 etc), I first got the list of the unique values in the variables, defined the list, then using some Numpy methods and a for loop to create bins of the required bin size</p><pre># Get list of unique values<br>df[‘column_name’].unique</pre><p>After creating the bins(intervals) with the above code, I matched the values in the variables to the intervals.</p><pre># Create an empty list to store the bin values<br>bin_values1 = []<br><br># Define the list of numbers<br>num = [#copy and paste the list returned from the above and remove the &#39; nan&#39; value]<br>    <br># Define the bin size<br>bin_size = 10<br><br># Calculate the number of bins needed<br>num_bins = int(np.ceil(max(num) / bin_size))<br><br># Create the bins <br>bins = [[] for _ in range(num_bins)]<br><br>#Display the list of bins<br>bin_list = []<br>for i, bin in enumerate(bins):<br>    bin_start = i * bin_size <br>    bin_end = (i + 1) * bin_size -1<br>    bin_list.append(f&quot;{bin_start} - {bin_end}&quot;)<br>bin_list<br><br># Iterate through the numbers and assign them to bins<br>for number in df[&#39;col1&#39;]:<br>    for bin in bin_list:<br>        bin_start, bin_end = map(int, bin_list.split(&quot; - &quot;))<br>        if bin_start &lt;= number &lt;= bin_end:<br>            bin_values1.append(bin)<br>            break<br>    else:<br>        bin_values1.append(None)<br>#Print the list of bin values for the numbers to check if the code worked correctly before replacing the values(numbers) in the variable with the bins(intervals)<br>for number, bin_value in zip(df[&#39;col1&#39;], bin_values1):<br>print(f&quot;{number}: {bin_value}&quot;)</pre><p>Then replace the numbers in the variable with the intervals created</p><pre>#replacing<br>df[&#39;col1&#39;] = bin_values1<br><br>#checking<br>df[&#39;col1&#39;].unique()</pre><p>Finally, replace the intervals with your number code ( as done in approach one)</p><pre>#Creating the dictionary<br>cat_to_num = <br>{<br>    &quot;interval1&quot;:1,<br>    &quot;interval2&quot;:2<br>     …<br>}<br>#replacing the values<br>df[&#39;col1&#39;] = df[&#39;col1&#39;].replace(cat_to_num)</pre><p><strong>Approach four</strong>: For questions in the questionnaire where respondents could choose more than one option, the cell values in the column will have those options selected separated by a comma. To clean up these columns and get them ready for analysis in SPSS, the best approach is to make each of the options a separate variable(column) and fill it up with ‘yes’ or ‘no’ depending on whether it was selected for that observation(row) or not. To do this, I created an empty list and simply used a for loop to fill it up based on a condition</p><pre>#create an empty list<br>options = []<br><br># Define the option<br>option = &#39;option1&#39;<br><br># this loop iterates through the column and checks if the cell value is first a string, then if option1 is in the cell value in each observation and appends the value 1 to the empty list(options) or 0 if it is not.<br>for i in df[&#39;column_name&#39;]:<br>    if isinstance(i, str) and option in i:<br>        options.append(1)<br>    else:<br>        options.append(0)<br>        <br># Creating a new column and assigning the values in the list(options) to it.<br>df[&#39;new_column&#39;] = options<br>#Check<br>df[&#39;new_column&#39;].value_counts()</pre><p>I repeated the above steps for all the options in the questionnaire for that particular kind of question.</p><p>I hope you enjoyed the read and gained insights on how to utilize the basic Python methods in cleaning up data and coding them into numbers for analysis in SPSS.</p><p>Please do not hesitate to drop questions if you have any in the comment sessions.</p><p>Please follow me on my social media handles</p><p><a href="https://twitter.com/home">X(formerly Twitter</a>)</p><p><a href="https://www.linkedin.com/in/caleb-ugorji/">LinkedIn</a></p><p>Thank you and see you next time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb539c9a81c2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I prepared a messy dataset for analysis for a client.]]></title>
            <link>https://medium.com/@ugorjicalebchijindu/how-i-prepared-a-messy-dataset-for-analysis-for-a-client-bbcf0191fcf6?source=rss-b330e45b2799------2</link>
            <guid isPermaLink="false">https://medium.com/p/bbcf0191fcf6</guid>
            <dc:creator><![CDATA[Caleb Chijindu Ugorji]]></dc:creator>
            <pubDate>Tue, 22 Aug 2023 03:39:15 GMT</pubDate>
            <atom:updated>2023-08-22T03:39:15.695Z</atom:updated>
            <content:encoded><![CDATA[<p>A client hit me up to analyse a dataset for a project. This data set is on sanitary pad use and has 1000 observations and 18 variables.</p><p>According to the client, the responses were collected and coded into Ms Excel. Some columns in the data set had so many unique values, misspelt words, etc.</p><p>I loaded this data into Pandas to clean them up. So I created a list of unique values for each of these columns and mapped their values to them — I tried using fuzzywuzzy for this task but the result was not that accurate, chat GPT had a better result. So I had Chat GPT do the mapping based on similarities in spelling and meaning of the values in the columns and the unique values in the list I created. Some values were mapped to more than one of the unique values and separated with a comma.</p><p><em>Below is the code for the explanation above for one column in the dataset(Q3b)</em></p><pre># Importing packages<br>import pandas as pd<br>import numpy as np<br><br># reading the excel sheet<br>df = pd.read_excel(&#39;excel pad project.xlsx&#39;, sheet_name=&#39;Sheet1&#39;)<br>df</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AwJQhw0xn_68_hlefOQ-Bg.jpeg" /><figcaption>output</figcaption></figure><p>How I prompted Chat GPT for the mapping task</p><p>categories= [‘absorbs well’, ‘suitable size’, ‘comfortable’, ‘non-irritable’, ‘always available’, ‘affordable’, ‘No reason’]</p><p>Above is a list of classes I created, I want you to map the following( the list of values of the column) to the classes above based on their meaning and similarity. One value can be mapped to more than one class separated by a comma</p><pre>categoriesQ3b = [&#39;absorbs well&#39;, &#39;suitable size&#39;, &#39;comfortable&#39;, &#39;non-irritable&#39;, &#39;always available&#39;, &#39;affordable&#39;, &#39;No reason&#39;, None, &#39;sticks well&#39;, &#39;Other&#39;]<br><br>mapping = {<br>    &#39;serves the purpose&#39;: &#39;Other&#39;,<br>    &#39;nill&#39;: &#39;No reason&#39;,<br>    &#39;best&#39;: &#39;Other&#39;,<br>    &#39;absorbing capacity&#39;: &#39;absorbs well&#39;,<br>    &#39;comfortable&#39;: &#39;comfortable&#39;,<br>    &#39;good absorbance and size&#39;: &#39;absorbs well, suitable size&#39;,<br>    &#39;good absorbance &#39;: &#39;absorbs well&#39;,<br>    &#39;comfort&#39;: &#39;comfortable&#39;,<br>    &#39;slim and good absorbance&#39;: &#39;absorbs well, suitable size&#39;,<br>    &#39;avaliabilty&#39;: &#39;always available&#39;,<br>    &#39;affordable,comortable and nice&#39;: &#39;affordable, comfortable&#39;,<br>    &#39;good absorbance&#39;: &#39;absorbs well&#39;,<br>    &#39;no stain while using&#39;: &#39;absorbs well&#39;,<br>    &#39;comfort and good absorbance&#39;: &#39;comfortable, absorbs well&#39;,<br>    &#39;good absorbance and no irritation&#39;: &#39;absorbs well, non-irritable&#39;,<br>    &#39;good comfort&#39;: &#39;comfortable&#39;,<br>    &#39;good absorbance and comfort&#39;: &#39;comfortable, absorbs well&#39;,<br>    &#39;good absorbance and affordability&#39;: &#39;absorbs well, affordable&#39;,<br>    &#39;big quantity plus pant liners&#39;: &#39;Other&#39;,<br>    &#39;good&#39;: &#39;Other&#39;,<br>    &#39;good absorbing capacity&#39;: &#39;absorbs well&#39;,<br>    &#39;quantity and affordable&#39;: &#39;affordable&#39;,<br>    &#39;affodable and good abborbance&#39;: &#39;affordable, absorbs well&#39;,<br>    &#39;affordability&#39;: &#39;affordable&#39;,<br>    &#39;absorbance&#39;: &#39;absorbs well&#39;,<br>    &#39;comfort and size&#39;: &#39;comfortable, suitable size&#39;,<br>    &#39;size, absorbance and comfort&#39;: &#39;comfortable, suitable size, absorbs well&#39;,<br>    &#39;costly&#39;: &#39;Other&#39;,<br>    &#39;nice an comfortable &#39;: &#39;comfortable&#39;,<br>    &#39;comfort  &#39;: &#39;comfortable&#39;,<br>    &#39;non irritating&#39;: &#39;non-irritable&#39;,<br>    &#39;affordable and comfortable&#39;: &#39;affordable, comfortable&#39;,<br>    &#39;ok&#39;: &#39;Other&#39;,<br>    &#39;comfort and absorbance&#39;: &#39;comfortable, absorbs well&#39;,<br>    &#39;good experience&#39;: &#39;Other&#39;,<br>    &#39;affordable, available, no irritation&#39;: &#39;affordable, always available, non-irritable&#39;,<br>    &#39;antibacteria&#39;: &#39;Other&#39;,<br>    &#39;hygine&#39;: &#39;Other&#39;,<br>    &#39;nill &#39;: &#39;No reason&#39;,<br>    &#39;availability&#39;: &#39;always available&#39;,<br>    &#39;more affordable and good absorbance&#39;: &#39;affordable, absorbs well&#39;,<br>    &#39;satisfied&#39;: &#39;Other&#39;,<br>    &#39;perfect&#39;: &#39;Other&#39;,<br>    &#39;no adverse effects&#39;: &#39;non-irritable&#39;,<br>    &#39;comfort and affordability&#39;: &#39;comfortable, affordable&#39;,<br>    &#39;has good absorbance&#39;: &#39;absorbs well&#39;,<br>    &#39;safe and comfortable&#39;: &#39;comfortable, non-irritable&#39;,<br>    &#39;comfort and lack of irritation&#39;: &#39;comfortable, non-irritable&#39;,<br>    &#39;good absorbent&#39;: &#39;absorbs well&#39;,<br>    &#39;good absorbance and long size&#39;: &#39;comfortable, suitable size&#39;,<br>    &#39;no irritation&#39;: &#39;non-irritable&#39;,<br>    &#39;afforadble and comfortable&#39;: &#39;affordable, comfortable&#39;,<br>    &#39;size and comfortable&#39;: &#39;comfortable, suitable size&#39;,<br>    &#39;affordable&#39;: &#39;affordable&#39;,<br>    &#39;good absorbace&#39;: &#39;absorbs well&#39;,<br>    &#39;affordable and good absorbance&#39;: &#39;affordable, absorbs well&#39;,<br>    &#39;comfort,no irritation,good absorbance&#39;: &#39;comfortable, non-irritable, absorbs well&#39;,<br>    &#39;choice&#39;: &#39;Other&#39;,<br>    &#39;good quality&#39;: &#39;Other&#39;,<br>    &#39;the best&#39;: &#39;Other&#39;,<br>    &#39;very comfortable&#39;: &#39;comfortable&#39;,<br>    &#39;completely satisfied&#39;: &#39;Other&#39;,<br>    &#39;lack of irritation and absorbs well&#39;: &#39;non-irritable, absorbs well&#39;,<br>    &#39;it absorns well&#39;: &#39;absorbs well&#39;,<br>    &#39;comfortable with good size&#39;: &#39;comfortable, suitable size&#39;,<br>    &#39;absorbes well&#39;: &#39;absorbs well&#39;,<br>    &#39;high absorbing capacity&#39;: &#39;absorbs well&#39;,<br>    &#39;affordable and good absorbing capacity&#39;: &#39;affordable, absorbs well&#39;,<br>    &#39;absorbing capacity,comfort,avaliabilty&#39;: &#39;absorbs well, comfortable, always available&#39;,<br>    &#39;affordable,good absorbing capacity&#39;: &#39;affordable, absorbs well&#39;,<br>    &#39;good and perfect&#39;: &#39;Other&#39;,<br>    &#39;long and good gum&#39;: &#39;suitable size, sticks well&#39;,<br>    &#39;good absorbance and comfortability&#39;: &#39;comfortable, absorbs well&#39;,<br>    &#39;no irritation,good absorbance&#39;: &#39;absorbs well, non-irritable&#39;,<br>    &#39;comfortability&#39;: &#39;comfortable&#39;,<br>    &#39;comfort and goodabsorbance&#39;: &#39;comfortable, absorbs well&#39;,<br>    &#39;serves well&#39;: &#39;Other&#39;,<br>    &#39;comfortable,avaliable&#39;: &#39;comfortable, always available&#39;,<br>    &#39;affordable,comfortable,good absorbance&#39;: &#39;affordable, comfortable, absorbs well&#39;,<br>    &#39;comfortable and affordable&#39;: &#39;comfortable, affordable&#39;,<br>    &#39;goof absorbance&#39;: &#39;absorbs well&#39;,<br>    &#39;good hold&#39;: &#39;sticks well&#39;,<br>    &#39;holds well&#39;: &#39;sticks well&#39;,<br>    &#39;is ok&#39;: &#39;Other&#39;,<br>    &#39;absorbs well&#39;: &#39;absorbs well&#39;,<br>    &#39;poor absorbance&#39;: &#39;Other&#39;,<br>    &#39;its ok&#39;: &#39;Other&#39;,<br>    &#39;comfortable and sticks well&#39;: &#39;comfortable, sticks well&#39;,<br>    &#39;good and safe&#39;: &#39;Other&#39;,<br>    &#39;portable and affordable&#39;: &#39;affordable, suitable size&#39;,<br>    &#39;comfortable and light&#39;: &#39;comfortable&#39;,<br>    &#39;it absorbes well and are comfortable&#39;: &#39;absorbs well, comfortable&#39;,<br>    &#39;its comfortable&#39;: &#39;comfortable&#39;,<br>    &#39;its satisfying&#39;: &#39;Other&#39;,<br>    &#39;avaliability&#39;: &#39;always available&#39;,<br>    &#39;good hygiene&#39;: &#39;Other&#39;,<br>    &#39;satisfactory&#39;: &#39;Other&#39;,<br>    &#39;best choice&#39;: &#39;Other&#39;,<br>    &#39;price&#39;: &#39;affordable&#39;,<br>    &#39;good choice&#39;: &#39;Other&#39;,<br>    &#39;comfortable annd absorbs well&#39;: &#39;comfortable, absorbs well&#39;,<br>    &#39;good and affortable&#39;: &#39;affordable&#39;,<br>    &#39;good packaging&#39;: &#39;Other&#39;,<br>    &#39;comfortable,good absorbance&#39;: &#39;comfortable, absorbs well&#39;,<br>    &#39;im used to it&#39;: &#39;Other&#39;,<br>    &#39;it doesn’t irritate&#39;: &#39;non-irritable&#39;,<br>    &#39;nothing special&#39;: &#39;No reason&#39;,<br>    &#39;nilll&#39;: &#39;No reason&#39;,<br>    &#39;affordable and easy to use&#39;: &#39;affordable&#39;,<br>    &#39;affordability,comfort,size,good absorbing&#39;: &#39;affordable, comfortable, suitable size, absorbs well&#39;,<br>    &#39;comfortable,affordable&#39;: &#39;comfortable, affordable&#39;,<br>    &#39;safe&#39;: &#39;Other&#39;,<br>    &#39;comfortable with good absorbance&#39;: &#39;comfortable, absorbs well&#39;,<br>    &#39;just satisfied&#39;: &#39;Other&#39;,<br>    &#39;affordable, comfy with no itch&#39;: &#39;affordable, comfortable, non-irritable&#39;,<br>    &#39;good size with absorbance&#39;: &#39;suitable size, absorbs well&#39;,<br>    &#39;comfy with no irritation&#39;: &#39;comfortable, non-irritable&#39;,<br>    &#39;no itch&#39;: &#39;non-irritable&#39;,<br>    &#39;all reasons listed above&#39;: &#39;Other&#39;,<br>    &#39;meets all requirement &#39;: &#39;Other&#39;,<br>    &#39;long and absorbs well&#39;: &#39;suitable size, absorbs well&#39;,<br>    &#39;absorbs well and reliable&#39;: &#39;absorbs well&#39;,<br>    &#39;suits all requirement&#39;: &#39;Other&#39;,<br>    &#39;long with good absorbance&#39;: &#39;suitable size, absorbs well&#39;,<br>    &#39;comfortable and doesn’t shake&#39;: &#39;comfortable, sticks well&#39;,<br>    &#39;no itch or irritation&#39;: &#39;non-irritable&#39;,<br>    &#39;its absorbs well and comfortable&#39;: &#39;absorbs well, comfortable&#39;,<br>    &#39;sticks well&#39;: &#39;sticks well&#39;,<br>    &#39;im ok&#39;: &#39;Other&#39;,<br>    &#39;lasts up to 8hrs&#39;: &#39;Other&#39;,<br>    &#39;absorbs and doesn’t irritate &#39;: &#39;absorbs well, non-irritable&#39;,<br>    &#39;highly costly&#39;: &#39;Other&#39;,<br>    &#39;they are nice&#39;: &#39;Other&#39;,<br>    &#39;its soft&#39;: &#39;Other&#39;,<br>    &#39;availability and affordability&#39;: &#39;always available, affordable&#39;,<br>    &#39;doesn’t stain&#39;: &#39;Other&#39;,<br>    &#39;cost effective&#39;: &#39;affordable&#39;,<br>    &#39;does not irritate&#39;: &#39;comfortable&#39;,<br>    &#39;absorbs well and doesn’t irritate&#39;: &#39;absorbs well, non-irritable&#39;,<br>    &#39;it serves&#39;: &#39;Other&#39;,<br>    &#39;no reason&#39;: &#39;No reason&#39;,<br>    &#39;absorbs well and comfortable&#39;: &#39;absorbs well, comfortable&#39;,<br>    &#39;long&#39;: &#39;suitable size&#39;,<br>    &#39;smells nice &#39;: &#39;Other&#39;<br>    <br>}<br><br>df[&#39;Q3b&#39;] = df[&#39;Q3b&#39;].replace(mapping)<br><br># checking unique values for Q3b<br>df.Q3b.unique()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*59T2gXzn-g4gUJDMGwZAUQ.jpeg" /><figcaption>Unique values in column q3b after the mapping</figcaption></figure><p>I repeated these steps for all the columns with numerous unique values and misspelt words.</p><p>Since I was going to analyse this data with SPSS, I saved the dataframe as an Excel file and loaded it into SPSS.</p><p>Dealing with variables with multiple responses in SPSS can be tedious. So I decided to get around the usual method of turning each unique value into a variable and then filling it up with a Yes or a No. This was going to be very tedious because the data had five columns with these multiple responses and each of the columns have about nine unique values. So, this implies creating nine more variables for each column and filling them up with Yes or No for the 1000 observations. This will result in 45 extra columns. The data will be so wide and this task will be extremely tedious.</p><p><em>So I decided to try another method.</em></p><p>I used the UNNEST(STRING_TO_ARRAY()) function in SQL to separate the variables that had comma-separated values. What this function does is it adds extra observations for each cell that has more than one unique value separated by a comma.</p><p>To do this, I had to load this data to PgAdmin. I encountered three problems when trying to do that</p><p>1. My pgAdmin binary path was at the default setting. I had to change it to C:\Program Files\PostgreSQL\15\bin.</p><p>2. I had this error message- ERROR: extra data after last expected column. This was because the data, which is a CSV file with a comma as the delimiter, I was trying to load into pgAdmin had columns with comma-separated values. So pgAdmin most likely treated both commas as indicating when to start a new column. To resolve this I had to re-save the data as a CSV file with semi-colon as the delimiter.</p><pre>#re-saving the file as a semicolon delimitered csv file<br>df.to_csv(&#39;sanitary_pad2.csv&#39;, sep=&#39;;&#39;, index=False)</pre><p>3. I had this error message- duplicate key value violates unique constraint “sanitary_pad_pkey”. The identification number column I used as the primary key in the table, had a duplicate value, hence pgAdmin could not process it. I had to drop the column and used the pandas&#39; df.reset_index() method to create a column that I used as the primary key.</p><pre>#dropping the identification number column<br>df.drop(&#39;identification number&#39;, axis= 1, inplace= True)<br><br># Resetting the index and creating a new unique identifier column<br>df[&#39;id&#39;] = df.reset_index().index + 1<br><br># Reordering the columns so that the id(unique identifier comes first)<br>df = df[[&#39;id&#39;, &#39;Age&#39;, &#39; Religion&#39;, &#39;Q1a&#39;, &#39;Q1b&#39;, &#39;Q1c&#39;, &#39;Q1d&#39;,<br>       &#39;Q2a&#39;, &#39;Q2b&#39;, &#39;Q2c&#39;, &#39;Q2d&#39;, &#39;Q3a&#39;, &#39;Q3b&#39;, &#39;Q3c&#39;, &#39;Q3d&#39;, &#39;Q4 &#39;, &#39;Q4a&#39;,<br>       &#39;Q4b&#39;]]<br>df</pre><p>Below is the query that does the job. This query selects every column in the table, It unnests the columns q3b, q3c, q3d, q4a, and q4b by adding a new row(observation) to the table for each cell with more than one unique value separated by a comma</p><pre>SELECT question_id, age, religion, q1a, q1b, q1c, q1d, q2a, q2b, q2c, q2d, q3a, <br>        UNNEST(STRING_TO_ARRAY(q3b, &#39;,&#39;)) as q3b,<br>        UNNEST(STRING_TO_ARRAY(q3c, &#39;,&#39;)) as q3c,<br>        UNNEST(STRING_TO_ARRAY(q3d, &#39;,&#39;)) as q3d,<br>        q4,<br>        UNNEST(STRING_TO_ARRAY(q4a, &#39;,&#39;)) as q4a,<br>        UNNEST(STRING_TO_ARRAY(q4b, &#39;,&#39;)) as q4b<br>FROM sp.sanitary_pad</pre><p>To Check if the output of the query is consistent with the original data</p><ul><li>I unnested all the columns and then used a CTE to count the table and group by q4a.</li><li>Then I unnested only q4a and used a CTE to count the table and group by q4a. I then compared the two outputs.</li><li>The two outputs are the same.</li><li>Just that the unnesting all the columns added some null values to the q4a column. Which is inconsequential.</li></ul><p><em>Code for step one</em></p><pre>with cte as (<br>SELECT question_id, age, religion, q1a, q1b, q1c, q1d, q2a, q2b, q2c, q2d, q3a, <br>        UNNEST(STRING_TO_ARRAY(q3b, &#39;,&#39;)) as q3b,<br>        UNNEST(STRING_TO_ARRAY(q3c, &#39;,&#39;)) as q3c,<br>        UNNEST(STRING_TO_ARRAY(q3d, &#39;,&#39;)) as q3d,<br>        q4,<br>        UNNEST(STRING_TO_ARRAY(q4a, &#39;,&#39;)) as q4a,<br>        UNNEST(STRING_TO_ARRAY(q4b, &#39;,&#39;)) as q4b<br>FROM sp.sanitary_pad<br>    )<br>    SELECT COUNT(*), q4a<br>    FROM cte<br>    GROUP BY q4a</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/349/1*XyGjhtH7gKbk-02BPega3g.jpeg" /><figcaption>step one output</figcaption></figure><p><em>Code for step two</em></p><pre>with cte as (<br>SELECT question_id, age, religion, q1a, q1b, q1c, q1d, q2a, q2b, q2c, q2d, q3a, <br>        UNNEST(STRING_TO_ARRAY(q4a, &#39;,&#39;)) as q4a<br>FROM sp.sanitary_pad<br>    )<br>    SELECT COUNT(*), q4a<br>    FROM cte<br>    GROUP BY q4a</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/337/1*Ls7_quiuV6CQBxoR7U1QyA.jpeg" /><figcaption>step two output</figcaption></figure><ul><li>I then saved the output of the query as a CSV file in pgAdmin. I loaded it into Pandas and resaved it as an Excel file because it is less complicated importing an Excel file into SPSS than a CSV file.</li></ul><h3>Data pre-processing in SPSS</h3><ul><li>SPSS recognizes trailing spaces and asks you to remove them during import files. So I removed the trailing spaces in the data.</li><li>SPSS records null values as system-missing values. But importing the data into SPSS it recorded the null values as empty strings. I tried a lot of methods to rectify this. Here is the one that worked.</li><li>I recoded the values into the same variable using a number to represent each value. Then I set the number as Value and the values as Label in the Variable view (Values) of each of the columns that had the null values.</li><li>I then converted the column data type to numeric</li><li>This automatically made the SPSS recognize the null values as system-missing values.</li></ul><p><em>Below is how I recoded the values</em></p><ul><li>RECODE q3b (‘absorbs well’=’1&#39;) (‘affordable’=’2&#39;) (‘always available’=’3&#39;) (‘comfortable’=’4&#39;) (‘sticks well’=’5&#39;) (‘suitable size’=’6&#39;) (‘non-irritable’=’7&#39;) (‘no reason’=’8&#39;) (‘other’=’9&#39;).</li><li>RECODE q3c (‘choice’=’1&#39;) (‘im used to it’=’2&#39;) (‘it all feels the same’=’3&#39;) (‘it is what I can ‘+ ‘afford’=’4&#39;) (‘no reason’=’5&#39;) (‘other’=’6&#39;).</li><li>RECODE q3d (‘absorbs poorly’=’1&#39;) (‘discomforting’=’2&#39;) (‘does not stick well’=’3&#39;) (‘expensive’=’4&#39;) (‘irritable’=’5&#39;) (‘not always available’=’6&#39;) (‘unsuitable’=’7&#39;) (‘no ‘+ ‘reason’=’8&#39;) (‘other’=’9&#39;).</li><li>RECODE q4a (‘cost’=’1&#39;) (‘discomfort’=’2&#39;) (‘poor absorbance’=’3&#39;) (‘unavailability’=’4&#39;) (‘irritability’=’5&#39;) (‘unsuitable size’=’6&#39;) (‘to try something new’=’7&#39;) (‘no reason’=’8&#39;) (‘other’=’9&#39;) (‘comfortable’=’2&#39;) (‘poor absorbance discomfort ‘=’3&#39;).</li><li>RECODE q4b (‘always available’=’1&#39;) (‘concerns of the effect’=’2&#39;) (‘good absorbance’=’3&#39;) (‘got ‘+ ‘used to it’=’4&#39;) (‘quite comfortable’=’5&#39;) (‘suitable size’=’6&#39;) (‘very affordable’=’7&#39;) (‘no ‘+ ‘reason’=’8&#39;) (‘other’=’9&#39;).</li></ul><p>I documented this cleaning process on my GitHub. Click to have a closer look at the codes — <a href="https://github.com/DataStance1/sanitary_pad_job">https://github.com/DataStance1/sanitary_pad_job</a></p><p>You can follow me on <a href="https://www.linkedin.com/in/caleb-ugorji/">LinkedIn</a> and <a href="https://twitter.com/calebugorji021">Twitter</a></p><p>Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbcf0191fcf6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Explaining How the Windows Functions Work in SQL]]></title>
            <link>https://medium.com/@ugorjicalebchijindu/explaining-how-the-windows-functions-work-in-sql-744e6a6b1533?source=rss-b330e45b2799------2</link>
            <guid isPermaLink="false">https://medium.com/p/744e6a6b1533</guid>
            <dc:creator><![CDATA[Caleb Chijindu Ugorji]]></dc:creator>
            <pubDate>Tue, 08 Aug 2023 06:15:00 GMT</pubDate>
            <atom:updated>2023-08-08T06:15:00.632Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/537/0*TqaTg0QKbSJwveGw.png" /><figcaption>preview image</figcaption></figure><p>I came across the window’s function for the first sometime in 2022. After finishing the Google Data Analytics Professional Course, I decided to try some advanced SQL on Kaggle. Well, you guessed it, I could not figure out what was going on in queries with the Windows clause.</p><p>In this article, I will try to explain how the Windows function in SQL works using a Query I used to answer one of Danny Ma’s case week one case study questions.</p><h3>What is the Windows Function</h3><p>A window function in SQL is a function that operates on a set of rows that are related to the current row. Window functions are similar to aggregate functions, but they do not group the rows together. Instead, each row retains its separate identity. Window functions can be used to calculate running totals, ranks, and other values that are related to the current row and the rows around it.</p><p><em>To fully understand how Windows functions work, you need to understand what is called ‘the Windows clause’.</em></p><p>The window_function is the name of the window function that you want to use. The window_clause specifies the set of rows that the window function will operate on.</p><p><strong>Components of the Windows Clause</strong></p><ul><li>PARTITION BY: This clause divides the rows into groups before the window function is applied.</li><li>ORDER BY: This clause specifies the order in which the rows will be processed by the window function.</li><li>ROWS: This clause specifies the range of rows that the window function will operate on.</li></ul><h4>The basic syntax of a Windows function</h4><pre>SELECT col1,<br>       col2, <br>       window_function() OVER (window_clause)<br>FROM table_name;</pre><p>The windows clause is introduced with the keyword OVER. You can think of the PARTITION BY keyword as the usual GROUP BY in a normal query but here it doesn’t produce a single output for each value in the column in which the data is been grouped. The ORDER BY in the Windows clause works pretty much the same way it does in a normal query. The ROWS keyword specified the range of rows that the window function will operate on.</p><p><em>Below is a simple query that calculates a three-day moving average of sales data</em></p><pre>SELECT<br>    product_id,<br>    sale_date,<br>    revenue,<br>    AVG(revenue) OVER (PARTITION BY product_id ORDER BY sale_date ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING) AS moving_avg<br>FROM<br>    sales;</pre><p>In this query, we are calculating a 3-day moving average of revenue for each product. The PARTITION BY clause divides the data by product, and the ORDER BY clause sorts the rows within each partition based on the sale date.</p><p>The window frame specification using ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING defines the range of rows included in the window frame for each row. It means that for each row, the window frame includes the current row and the immediately preceding and following rows based on the order defined by ORDER BY.</p><p><em>Now let&#39;s look at the query I used to answer one of Danny Ma’s week one SQL challenge case study questions</em></p><p><strong>Question six: Which item was purchased first by the customer after they became a member?</strong></p><p><em>Below are snips of the tables in the database and their entity relationship diagram</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*TrwOVZwlsZ9lcK5CGk8gwA.jpeg" /><figcaption>Sales table</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*PexiKd5tGnOSpHJbQq2kUw.jpeg" /><figcaption>menu table</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*QsGYDBQa171peQ4VrVg-dw.jpeg" /><figcaption>member table</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*nTWwoJzYQOhXSTugKclWaA.jpeg" /><figcaption>Entity Relationship Diagram</figcaption></figure><h4>My Query</h4><pre>WITH cte AS<br>(<br> SELECT mb.customer_id, <br>     m.product_name, <br>     s.order_date, <br>     mb.join_date,<br>     RANK() OVER (PARTITION BY mb.customer_id ORDER BY s.order_date) AS rank<br> FROM dannys_diner.sales AS s<br> JOIN dannys_diner.menu AS m<br>  ON s.product_id = m.product_id<br> JOIN dannys_diner.members mb<br>  ON s.customer_id = mb.customer_id<br> WHERE s.order_date &gt;= mb.join_date<br>)<br>SELECT *<br>FROM cte<br>WHERE rank = 1</pre><h4>Explanation</h4><p>This SQL query uses a Common Table Expression (CTE) to calculate the rank of the first purchase made by each customer after they joined a membership program at Danny’s Diner.</p><p>Breaking down the query step-by-step:</p><ol><li>WITH cte AS: This starts the definition of the Common Table Expression (CTE) named &quot;cte,&quot; which acts as a temporary result set.</li><li>The CTE selects columns from three tables: sales, menu, and members.</li></ol><ul><li>mb.customer_id: The customer ID from the members table.</li><li>m.product_name: The product name from the menu table.</li><li>s.order_date: The order date from the sales table.</li><li>mb.join_date: The join date of the customer from the members table.</li></ul><p>3. RANK() OVER (PARTITION BY mb.customer_id ORDER BY s.order_date) AS rank: This is a window function RANK() used in the CTE. It assigns a rank to each row based on the order date of the customer&#39;s purchase within their partition. The partitioning is done by customer_id, and the ranking is done in ascending order of order_date.</p><p>4. The FROM clause specifies the tables used in the CTE, and the JOIN conditions connect the appropriate columns from the sales, menu, and members tables based on their respective IDs.</p><p>5. The WHERE clause filters the rows to only include orders where the order_date is greater than or equal to the join_date of the customer, ensuring that only orders made after the customer joined are considered.</p><p>6. The outer query selects all columns from the CTE cte.</p><p>7. The WHERE clause of the outer query filters the results to only include rows where the rank is equal to 1. This effectively retrieves the first purchase made by each customer after they joined the membership program.</p><p><em>In summary, this query calculates the rank of each order made by customers after they joined the membership program, and then it selects the rows where the rank is equal to 1, which represents the first purchase made by each customer after joining the program.</em></p><p>If you would like to solve this case study, click<a href="https://8weeksqlchallenge.com/case-study-1/"> [here]</a></p><p>I have carefully and clearly documented my solutions to all the case study questions <a href="https://github.com/DataStance1/Dannys_Diner/blob/main/week_one_sql.sql">[here]</a></p><p>I hope this article helps you understand Windows function as it is a powerful tool employed in carrying out advanced analysis.</p><p><em>You can follow me on social media</em></p><p>Twitter: <a href="https://twitter.com/calebugorji021">https://twitter.com/calebugorji021</a></p><p>LinkedIn: <a href="https://linkedin.com/in/caleb-ugorji">https://linkedin.com/in/caleb-ugorji</a></p><p>I am open to any data analysis role and collaboration.</p><p><em>Thank you for reading and engaging. Bye for now!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=744e6a6b1533" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Explaining Recursive Query in SQL]]></title>
            <link>https://medium.com/@ugorjicalebchijindu/explaining-recursive-query-in-sql-38c043fcc740?source=rss-b330e45b2799------2</link>
            <guid isPermaLink="false">https://medium.com/p/38c043fcc740</guid>
            <dc:creator><![CDATA[Caleb Chijindu Ugorji]]></dc:creator>
            <pubDate>Sat, 05 Aug 2023 12:36:04 GMT</pubDate>
            <atom:updated>2023-08-05T12:36:04.396Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/439/1*ZIGTWF4wPegsJEi6xumTsQ.png" /><figcaption>preview image</figcaption></figure><p>In the last project I did with SQL, I wrote a recursive query to generate a table as part of the challenge questions.</p><p>Guess what? It was my first time writing one and it took me some time to figure it out.</p><p>In this article, I am going to explain what a recursive query means and how to write one using the same query I wrote to answer the challenge question.</p><h4>What is a Recursive Query?</h4><p>A recursive query in SQL is a query that calls itself repeatedly until it reaches a termination condition. It refers back to itself during its execution, allowing you to perform hierarchical or self-referencing operations on hierarchical data or data with a recursive relationship.</p><p>To understand recursive queries, one needs to be familiar with its two main components:</p><ol><li>Common Table Expression (CTE): A Common Table Expression is a named temporary result set within an SQL query that can be referenced within the main query. It starts with the WITH keyword and is often used to simplify complex queries or break down the logic into smaller, more manageable parts.</li><li>Recursive Part: The recursive part of the CTE refers back to the CTE itself. It is essential to have two parts in a recursive CTE: the initial (or anchor) part and the recursive part. The initial part establishes the base case or starting point of the recursion, and the recursive part iteratively builds upon the initial result set.</li></ol><p><strong>The basic structure of a recursive query is as follows</strong></p><pre>WITH RECURSIVE cte AS (<br>  -- Base(anchor) query<br>  ...<br>  UNION ALL<br>  -- Recursive query<br>  ...<br>)<br>SELECT ...<br>FROM cte;</pre><p><strong>Let’s go through the steps of how a recursive CTE works:</strong></p><ol><li>The initial part of the CTE retrieves the base case or starting rows from the base table based on some conditions.</li><li>The recursive part then uses the CTE itself as if it were a table to build on the initial result set. It filters, joins, or performs other operations on the previous result set to generate the next iteration.</li><li>The process continues iteratively until the recursive part produces an empty result set or reaches a termination condition, at which point the recursion stops, and the final result set is returned.</li></ol><p><em>Now let’s take a look at the query I use in the case study to answer the challenge question.</em></p><h3>Challenge question</h3><p>The Foodie-Fi team wants you to create a new payments table for the year 2020 that includes amounts paid by each customer in the subscriptions table with the following requirements:</p><ol><li>Monthly payments always occur on the same day of the month as the original start_date of any monthly paid plan</li><li>Upgrades from basic to monthly or pro plans are reduced by the current paid amount in that month and start immediately</li><li>Upgrades from pro monthly to pro annual are paid at the end of the current billing period and also start at the end of the month period</li><li>Once a customer churns they will no longer make payments</li></ol><p>Below are the tables and their entity relationship diagram</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*W-5v0erOifCB3lyuxyQoYQ.jpeg" /><figcaption>Plan table</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*-tRIL4ftSustJG8NkQo6Xg.jpeg" /><figcaption>Subscription table</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*klBB89OXPeFPAPrPsHaKnw.png" /><figcaption>Entity Relationship Diagram</figcaption></figure><h3>The Full Recursive Query</h3><pre>WITH RECURSIVE dateRecursion AS (<br>    SELECT  s.customer_id,<br>            s.plan_id,<br>            p.plan_name,<br>            s.start_date::timestamp AS payment_date,<br>            CASE <br>      --if a customer kept using the current plan, last_date = &#39;2020-12-31&#39;<br>              WHEN LEAD(s.start_date) OVER(PARTITION BY s.customer_id ORDER BY s.start_date) IS NULL THEN &#39;2020-12-31&#39;::DATE<br>      --if a customer changed the plan, last_date = (month difference between start_date and changing date) + start_date<br>              ELSE s.start_date + (EXTRACT(YEAR FROM LEAD(s.start_date) OVER(PARTITION BY s.customer_id ORDER BY s.start_date))<br>                                    - EXTRACT(YEAR FROM s.start_date)) * INTERVAL &#39;1 year&#39;<br>               + (EXTRACT(MONTH FROM LEAD(s.start_date) OVER(PARTITION BY s.customer_id ORDER BY s.start_date)) <br>                  - EXTRACT(MONTH FROM s.start_date)) * INTERVAL &#39;1 month&#39;<br>              END AS last_date,<br>            p.price AS amount<br>    FROM foodie_fi.subscriptions s<br>    JOIN foodie_fi.plans p <br>        ON s.plan_id = p.plan_id<br>  --exclude trials because they didn&#39;t generate payments <br>    WHERE p.plan_name NOT IN (&#39;trial&#39;)<br>    AND EXTRACT(YEAR FROM start_date) = 2020<br>    <br>  UNION ALL<br>    <br>    SELECT customer_id,<br>           plan_id,<br>           plan_name,<br>    --increment payment_date by monthly<br>           payment_date + INTERVAL &#39;1 month&#39; AS payment_date,<br>           last_date,<br>           amount<br>    FROM dateRecursion<br>  --stop incrementing when payment_date = last_date<br>    WHERE payment_date + INTERVAL &#39;1 month&#39; &lt;= last_date<br>    AND plan_name != &#39;pro annual&#39;<br>)<br>--Create a new table [payments]<br>SELECT customer_id,<br>       plan_id,<br>       plan_name,<br>        payment_date,<br>        amount,<br>        ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY payment_date) AS payment_order<br>INTO foodie_fi.payment<br>FROM dateRecursion<br>-- Exclude churns<br>WHERE amount IS NOT NULL;</pre><p><em>Looks like a lot right? I also felt like this when I was figuring it out. Below is the breakdown of the query</em>.</p><h4>The anchor or base query</h4><pre>WITH RECURSIVE dateRecursion AS (<br>    SELECT  s.customer_id,<br>            s.plan_id,<br>            p.plan_name,<br>            s.start_date::timestamp AS payment_date,<br>            CASE <br>      --if a customer kept using the current plan, last_date = &#39;2020-12-31&#39;<br>              WHEN LEAD(s.start_date) OVER(PARTITION BY s.customer_id ORDER BY s.start_date) IS NULL THEN &#39;2020-12-31&#39;::DATE<br>      --if a customer changed the plan, last_date = (month difference between start_date and changing date) + start_date<br>              ELSE s.start_date + (EXTRACT(YEAR FROM LEAD(s.start_date) OVER(PARTITION BY s.customer_id ORDER BY s.start_date))<br>                                    - EXTRACT(YEAR FROM s.start_date)) * INTERVAL &#39;1 year&#39;<br>               + (EXTRACT(MONTH FROM LEAD(s.start_date) OVER(PARTITION BY s.customer_id ORDER BY s.start_date)) <br>                  - EXTRACT(MONTH FROM s.start_date)) * INTERVAL &#39;1 month&#39;<br>              END AS last_date,<br>            p.price AS amount<br>    FROM foodie_fi.subscriptions s<br>    JOIN foodie_fi.plans p <br>        ON s.plan_id = p.plan_id<br>  --exclude trials because they didn&#39;t generate payments <br>    WHERE p.plan_name NOT IN (&#39;trial&#39;)<br>    AND EXTRACT(YEAR FROM start_date) = 2020</pre><p>This base query is a recursive Common Table Expression (CTE) called dateRecursion. The CTE has the following columns:</p><ul><li>customer_id: Identifier for each customer.</li><li>plan_id: Identifier for the subscription plan.</li><li>plan_name: Name of the subscription plan.</li><li>payment_date: Initial payment date for each customer&#39;s subscription (converted to a timestamp).</li><li>last_date: The last date of the subscription, determined based on the customer&#39;s subscription history.</li><li>amount: The price (amount) associated with the subscription plan.</li></ul><p>The initial part of the CTE( base query) selects data from two tables: subscriptions (aliased as s) and plans (aliased as p). It filters out trial plans and only includes subscriptions that have a start_date in the year 2020. The last_date column is calculated based on the logic described in the comments:</p><ul><li>If a customer kept using the current plan, last_date is set to &#39;2020-12 31&#39;.</li><li>If a customer changed the plan, last_date is calculated as the difference in months and years between the start_date and the start_date of the next plan, added to the start_date.</li></ul><h4>The recursive part of the query</h4><pre>UNION ALL<br>    <br>    SELECT customer_id,<br>           plan_id,<br>           plan_name,<br>    --increment payment_date by monthly<br>           payment_date + INTERVAL &#39;1 month&#39; AS payment_date,<br>           last_date,<br>           amount<br>    FROM dateRecursion<br>  --stop incrementing when payment_date = last_date<br>    WHERE payment_date + INTERVAL &#39;1 month&#39; &lt;= last_date<br>    AND plan_name != &#39;pro annual&#39;</pre><p>This part uses the UNION ALL clause to refer back to the dateRecursion CTE itself. It increments the payment_date by one month (using payment_date + INTERVAL &#39;1 month&#39;) and adds new rows to the CTE while keeping the original columns (customer_id, plan_id, plan_name, last_date, and amount) unchanged.</p><p>The recursion continues until the payment_date is equal to or greater than the last_date for each customer, and the plan name is not &#39;pro annual&#39;.</p><h4>The main query (To create the payments table)</h4><pre>--Create a new table [payments]<br>SELECT customer_id,<br>       plan_id,<br>       plan_name,<br>        payment_date,<br>        amount,<br>        ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY payment_date) AS payment_order<br>INTO foodie_fi.payment<br>FROM dateRecursion<br>-- Exclude churns<br>WHERE amount IS NOT NULL;</pre><p>After the recursive CTE is complete, the final result set is used to create a new table called payments using the INTO clause. The ROW_NUMBER() function is used to assign a payment order for each customer, based on the ascending order of the payment_date.</p><p>The final SELECT statement retrieves the results from the recursive CTE and inserts them into the new payments table, excluding any rows where the amount is NULL (presumably representing churned or inactive customers).</p><h4>The output</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*BrNAqKaiYMOxVPy0EsWP7w.jpeg" /></figure><p>In summary, the query calculates the payment dates and amounts for each customer’s subscription based on their subscription history and creates a new table called payments to store this information. The recursive CTE is responsible for generating the payment dates iteratively until the end of the subscription period for each customer.</p><p>If you would like to solve this case study, click <a href="https://8weeksqlchallenge.com/case-study-3/">here</a></p><p>I have carefully and clearly documented my solutions to all the case study questions<a href="https://github.com/DataStance1/Foodie_fi_SQL_Case_Study_Solution"> [here]</a></p><p>I also created a summary dashboard of some business metrics and findings from the dataset<a href="https://public.tableau.com/app/profile/caleb.chijindu.ugorji/viz/Foodie_fisummarydashboard/Dashboard3?publish=yes"> [here]</a></p><p>I hope this article helps you understand recursive queries as it is a powerful tool employed in carrying out advanced analysis.</p><p>You can follow me on social media</p><p>Twitter: <a href="https://twitter.com/calebugorji021">https://twitter.com/calebugorji021</a></p><p>LinkedIn: <a href="https://linkedin.com/in/caleb-ugorji">https://linkedin.com/in/caleb-ugorji</a></p><p>I am open to any data analysis role. Thank you for reading and engaging</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38c043fcc740" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Danny Ma’s Week Two Solution — PIZZA RUNNER]]></title>
            <link>https://medium.com/@ugorjicalebchijindu/danny-mas-week-two-solution-pizza-runner-870863953e2a?source=rss-b330e45b2799------2</link>
            <guid isPermaLink="false">https://medium.com/p/870863953e2a</guid>
            <dc:creator><![CDATA[Caleb Chijindu Ugorji]]></dc:creator>
            <pubDate>Wed, 24 May 2023 18:20:30 GMT</pubDate>
            <atom:updated>2023-05-24T18:20:30.552Z</atom:updated>
            <content:encoded><![CDATA[<p>Danny Ma’s Week Two Solution — <em>PIZZA RUNNER</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BlecG3ENX9f0FGwE.png" /></figure><p>Hey guys, long time no see. I have actually been very busy finishing up school.</p><p>So, I have published my solutions to the week two case study on GitHub following my last publication here.</p><p>Here are some insights got and recommendations for Pizza Runner</p><p><strong>INSIGHT</strong></p><ul><li>Meat_lovers sells more than vegetarian</li><li>Wednesdays and Saturdays are the days with the highest sales</li><li>customers order pizzas more into the day and in the evening than early morning hours</li><li>Many of the pizzas ordered had either exclusions or extras perhaps it is time to add another type of pizza with different ingredients</li><li>Bacon is the most commonly added extra</li><li>Cheese is the most common exclusion</li><li>Meat lovers&#39; orders have more alterations to their ingredients than vegetarian orders, with cheese being excluded most and bacon being added most.</li><li>The most used ingredient is Bacon</li></ul><p><strong>RECOMMENDATIONS</strong></p><ul><li>Danny Ma’s runners travelled long distances to deliver the pizza, which is not ideal for a starting business. Danny Ma should consider creating an advert to target people closer to the pizza factory</li><li>Since there is always an alteration in the pizza ingredients, it is quite about time to introduce a new pizza type with a different recipe based on the popular alterations</li><li>Danny Ma should develop an effective way of collecting customer feedback as this is very important for a budding business</li><li>Since bacon is a commonly used ingredient, Danny Ma should ensure not to run out of it.</li><li>Danny should look into the preparation and delivery time of the ordered pizza. Pizza with Order_id 8 took a long time to deliver</li><li>Introduction of the new pizza type — Supreme should be followed with an advertisement</li><li>Danny should have a discount or loyalty program for repeat customers</li></ul><p>Here is the link to my GitHub <a href="https://github.com/DataStance1/Pizza_runner_solutions">https://github.com/DataStance1/Pizza_runner_solutions</a></p><p>Thank you for reading, and I hope you find this helpful.</p><p>I would also appreciate your feedback</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=870863953e2a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Danny Ma’s 8-week SQL challenge: Case study 2 (Data wrangling)]]></title>
            <link>https://medium.com/@ugorjicalebchijindu/danny-mas-8-week-sql-challenge-case-study-2-data-wrangling-51ee95f0fb7a?source=rss-b330e45b2799------2</link>
            <guid isPermaLink="false">https://medium.com/p/51ee95f0fb7a</guid>
            <dc:creator><![CDATA[Caleb Chijindu Ugorji]]></dc:creator>
            <pubDate>Thu, 06 Apr 2023 20:18:03 GMT</pubDate>
            <atom:updated>2023-04-06T20:18:03.318Z</atom:updated>
            <content:encoded><![CDATA[<p>Hey guys, I am still solving Danny Ma’s 8-week SQL challenge, and this case study two is challenging😂. The data provided was messy and needed to be cleaned. SQL is not my favourite tool for data wrangling, but I had to try it.</p><p>In this article, I will walk you through how I cleaned the data provided before tackling the case study questions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rqxriZzlYw7N4gcX.png" /></figure><p><strong>Introduction</strong></p><p>Pizza Runner is Danny’s idea of <em>uberizing </em>pizza delivery. He has provided me, the data analyst, with data from the business to analyze and give him insights. But the data provided is messy and needs some cleaning.</p><p><strong>Problem Statement</strong></p><p>Danny has prepared an entity relationship diagram of his database design but requires further assistance to clean his data and apply some basic calculations so he can better direct his runners and optimize Pizza Runner’s operations.</p><p><strong>Available data</strong></p><p>Danny Ma provided 6 tables</p><p><strong>Entity Relationship Diagram</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*ruKVMOsLGsgDGrRMOjfgHg.jpeg" /></figure><h4>Table 1: runners</h4><p>The <strong>runners </strong>table shows the registration_date for each new runner</p><h4>Table 2: customer_orders</h4><p>Customer pizza orders are captured in the customer_orders table with one row for each individual pizza that is part of the order.</p><h4>Table 3: runner_orders</h4><p>After each order is received through the system, they are assigned to a runner; however, not all orders are fully completed and can be cancelled by the restaurant or the customer.</p><h4>Table 4: pizza_names</h4><p>At the moment, Pizza Runner only offers two types of pizza: meat lovers and vegetarians.</p><h4>Table 5: pizza_recipes</h4><p>Eachpizza_id has a standard set of toppings which are used as part of the pizza recipe.</p><h4>Table 6: pizza_toppings</h4><p>This table contains all of the topping_name values with their corresponding topping_id value</p><p><strong>DATA WRANGLING TASK</strong></p><p>Data wrangling involves three steps; data gathering, assessment, and cleaning.</p><p><strong>Data gathering:</strong> The data for this case study was provided by Danny Ma and can be found here- <a href="https://8weeksqlchallenge.com/case-study-2/">https://8weeksqlchallenge.com/case-study-2/.</a></p><p><strong>Assessing the data: </strong>It is good practice first to assess the data provided before jumping into the cleaning process properly. The data was accessed visually to fish out the data quality and tidiness issues</p><pre>  SELECT * <br>  FROM customer_orders;<br><br>  SELECT * <br>  FROM pizza_names;<br><br>  SELECT * <br>  FROM pizza_recipes;<br><br>  SELECT * <br>  FROM pizza_toppings;<br><br>  SELECT * <br>  FROM runner_orders;<br><br>  SELECT * <br>  FROM runners;</pre><p>Aha, upon visual assessment, some data quality and tidiness issues were discovered in the customer_orders, runners, pizza_names and</p><p>The data quality and tidiness issues identified.</p><p><strong>Customer_orders table.</strong></p><ol><li>The ‘null’ character instead of NULL and the empty cells in the extras and exclusion table</li><li>The comma-separated values in the extras and exclusions columns</li></ol><p><strong>Runner_orders table.</strong></p><ol><li>The ‘null’ character instead of NULL and the empty cells in the pickup_time, distance, duration, and cancellation columns</li><li>The ‘km’ and the ‘minutes’ inconsistency in the distance and duration columns</li><li>the wrong data type for the pickup_time, distance, and duration column</li><li>Non- descriptive column names for the distance and duration columns</li></ol><p><strong>Pizza_recipes table.</strong></p><ol><li>The comma-separated values in the toppings column</li><li>wrong data type for the toppings column</li></ol><p><strong>DATA CLEANING:</strong></p><p>I approached this cleaning process with the define-code-test model.</p><p><strong>Customer_orders table:</strong></p><p><strong><em>Issue #1</em></strong></p><p>Define:</p><p>Set the ‘null’ and empty characters in the extras and exclusions columns to actual NULL values and update the table</p><p>Code:</p><pre>UPDATE customer_orders<br>SET exclusions = NULL<br>WHERE exclusions = &#39;&#39; OR exclusions = &#39;null&#39;;<br>  <br>UPDATE customer_orders<br>SET extras = NULL<br>WHERE extras = &#39;&#39; OR extras = &#39;null&#39;</pre><p>Test:</p><pre>SELECT *<br>FROM customer_orders;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*0j8XRxAj8K9DWESXY5Frjg.jpeg" /><figcaption>output</figcaption></figure><p><strong>Runner_orders table:</strong></p><p><strong><em>Issue #1</em></strong></p><p>Define:</p><p>Set the ‘null’ and the empty characters in the pickup_time, distance, duration, and cancellation columns to actual NULL and update the table</p><p>Code:</p><pre>UPDATE runner_orders<br>SET pickup_time = NULL<br>WHERE pickup_time = &#39;null&#39;;<br><br>UPDATE runner_orders<br>SET distance = NULL<br>WHERE distance = &#39;null&#39;;<br><br>UPDATE runner_orders<br>SET duration = NULL<br>WHERE duration = &#39;null&#39;;<br><br>UPDATE runner_orders<br>SET cancellation = NULL<br>WHERE cancellation = &#39;null&#39; OR cancellation = &#39;&#39;;<br></pre><p>Test:</p><pre>SELECT *<br>FROM pizza_runner.runner_orders</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*vTyw2tD3ERpwATox7yfwqA.jpeg" /><figcaption>Output</figcaption></figure><p><strong><em>Issue #2</em></strong></p><p>Define:</p><p>Replace the &quot;km&quot; in the distance column with spaces and later trim the spaces. Remove the &quot;mins&quot; and &quot;minutes&quot; in the duration column by using the substring function to select the first two strings.</p><p>Code:</p><pre>UPDATE runner_orders<br>SET distance = CASE WHEN distance = &#39;null&#39; THEN NULL <br>               WHEN distance LIKE &#39;%km&#39; THEN <br>                  TRIM(REPLACE(distance, &#39;km&#39;, &#39;&#39;)) ELSE distance END;<br>            <br>UPDATE runner_orders<br>SET duration = CASE WHEN duration LIKE &#39;%min%&#39; SUBSTRING(duration, 1, 2)<br>               ELSE duration END;</pre><p>Test:</p><pre>SELECT *<br>FROM pizza_runner.runner_orders</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*DsXcsTlkBFLFv1Yn9P_dFQ.jpeg" /><figcaption>Output</figcaption></figure><p><strong><em>Issue #3 and #4</em></strong></p><p>Define:</p><p>Rename the distance and duration columns to distance_km and duration_min, respectively, using the ALTER TABLE statement and the RENAME COLUMN function. Also, using the same statement and the ALTER COLUMN function, change the pickup_time, distance, and duration column datatypes to timestamp, decimal, and integer.</p><p>Code:</p><pre>--Renaming the distance and duration columns to be more descriptive (adding the unit measurements).<br><br>ALTER TABLE pizza_runner.runner_orders<br>RENAME COLUMN distance TO distance_km;<br><br>ALTER TABLE pizza_runner.runner_orders<br>RENAME COLUMN duration TO duration_min;<br><br>-- changing the column data types<br><br>ALTER TABLE pizza_runner.runner_orders<br>ALTER COLUMN pickup_time TYPE Timestamp USING pickup_time::timestamp;<br><br>ALTER TABLE pizza_runner.runner_orders<br>ALTER COLUMN distance_km TYPE DECIMAL USING distance_km::DECIMAL;<br><br>ALTER TABLE pizza_runner.runner_orders<br>ALTER COLUMN duration_min TYPE INTEGER USING duration_min::INTEGER; </pre><p>Test</p><pre>SELECT *<br>FROM pizza_runner.runner_orders</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*MoQcWPdlljABDVfQ4FqP3A.jpeg" /><figcaption>Output</figcaption></figure><p><strong>Pizza_recipes table</strong></p><p><strong><em>Issue #1 and #2</em></strong></p><p>Define:</p><p>Create a table clean_pizza_recipes and separate the strings <br>into separate rows using the UNNEST function and the STRING_TO_ARRAY function. Change the data type of the toppings column to an integer</p><p>Code:</p><pre>-- creating the table<br><br>DROP TABLE IF EXISTS clean_pizza_recipes;<br>SELECT pizza_id, UNNEST(STRING_TO_ARRAY(toppings, &#39;,&#39;)) AS toppings<br>INTO clean_pizza_recipes<br>FROM pizza_runner.pizza_recipes;<br><br>-- change the datatype of the toppings column to int<br>ALTER TABLE pizza_runner.clean_pizza_recipes<br>ALTER COLUMN toppings TYPE INTEGER USING toppings::INTEGER;<br></pre><p>Test:</p><pre>SELECT *<br>FROM pizza_runner.clean_pizza_recipes</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/237/1*9Cm1lSHDz6q7quKtr72O-w.jpeg" /><figcaption>Output</figcaption></figure><p>So far, so good, huh?</p><p>I did not separate the rows with the comma-separated values in the customer_order table.</p><p>Well, I did that while solving one of the case study questions that I will publish next and soonest.</p><p>Thank you for reading. I hope you enjoyed the reading and were able to understand my thought process.</p><p>I would also appreciate your feedback. If you want to have a closer look at the codes, I have posted the codes on my GitHub-</p><p><a href="https://github.com/DataStance1/data_cleaning_with_SQL/blob/main/week_two_data_cleaning.sql">data_cleaning_with_SQL/week_two_data_cleaning.sql at main · DataStance1/data_cleaning_with_SQL</a></p><p>Don’t forget to say hi on <a href="https://twitter.com/DataStance">Twitter </a>and <a href="http://linkedin.com/in/caleb-ugorji">LinkedIn</a></p><p>Bye for now!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51ee95f0fb7a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My solution to Danny Ma 8 Week SQL Challenge: Case Study One]]></title>
            <link>https://medium.com/@ugorjicalebchijindu/my-solution-to-danny-ma-8-week-sql-challenge-case-study-one-5f5b5633784b?source=rss-b330e45b2799------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f5b5633784b</guid>
            <dc:creator><![CDATA[Caleb Chijindu Ugorji]]></dc:creator>
            <pubDate>Sat, 11 Mar 2023 18:07:11 GMT</pubDate>
            <atom:updated>2023-03-11T18:07:11.767Z</atom:updated>
            <content:encoded><![CDATA[<p>I decided to hop on this challenge to practice my SQL skills and gain more proficiency in it. Here I will present my solutions to the questions in Case Study one. It was pretty fun solving these questions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*A1Qp2WoSXj6h_pwq.png" /></figure><p><strong>Introduction:</strong> Danny Diner is a restaurant that needs the assistance of a data analyst (me) to help make informed business decisions that will keep the restaurant afloat.</p><p><strong>Problem statement: </strong>Danny wants to use the data to answer a few simple questions about his customers, especially about their visiting patterns, how much money they’ve spent, and which menu items are their favourites. Having this deeper connection with his customers will help him deliver a better and more personalized experience for his loyal customers.</p><p>He plans on using these insights to help him decide whether he should expand the existing customer loyalty program</p><p>For this case study, three datasets were provided</p><ol><li>sales</li><li>menu</li><li>members</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*nTWwoJzYQOhXSTugKclWaA.jpeg" /></figure><p><strong>Case Study Questions and Solutions</strong></p><p>#1: <strong>What is the total amount each customer spent at the restaurant?</strong></p><p>To answer this question, I performed a simple join because the information needed to answer this question is on two different tables; the sales table and the menu table.</p><pre>SELECT  s.customer_id, <br>        SUM(m.price) total_amount<br>FROM dannys_diner.sales AS s<br>JOIN dannys_diner.menu m<br> ON s.product_id = m.product_id<br>GROUP BY s.customer_id<br>ORDER BY total_amount DESC</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*AQ-Uo7wqhImsbZf-wIe8cw.jpeg" /><figcaption>Output</figcaption></figure><p>Brief explanation: Here I selected the customer_Id column from the sales table and took the sum of the price column from the menu table,<br>joined the two tables on a common field, product_id and then grouped by the customer_id</p><p>#2: <strong>How many days has each customer visited the restaurant?</strong></p><p>To get the number of days each customer visited the restaurant, I selected the customer_id and then counted the distinct date each customer visited</p><pre>SELECT customer_id, <br>       COUNT (DISTINCT (order_date)) as num_of_visits<br>FROM dannys_diner.sales<br>GROUP BY customer_id<br>ORDER BY num_of_visits DESC</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/302/1*jBTLmGJPI1pcqbfZIfg4Lg.jpeg" /><figcaption>Output</figcaption></figure><p>Brief explanation: The Count () and Distinct() functions count the distinct date and the Group by clause groups the count by the customer_id</p><p>#3: <strong>What was the first item from the menu purchased by each customer?</strong></p><p>The easiest approach to solving this question for me was using the windows function Rank(), partitioning the window by customer_id and ordering it by the order_date</p><pre>WITH cte1 AS <br>(<br> SELECT s.customer_id, <br>        m.product_name, <br>        s.order_date,<br>        DENSE_RANK() OVER (PARTITION BY s.customer_id ORDER BY s.order_date) AS rank<br> FROM dannys_diner.sales s<br> JOIN dannys_diner.menu m<br>  ON s.product_id = m.product_id<br>)<br>SELECT *<br>FROM cte1<br>WHERE rank = 1</pre><p>Brief explanation: The code above selects the customer_id, and order_date from the sales table and the product_name from the menu’s table. The dense_rank() function returns the rank of rows as specified by the item in the order_by clause. The output is partitioned by the customer_id</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*SXBMmQ6HkvGKwlUIdSC-Rw.jpeg" /><figcaption>the output of the inner query (cte1)</figcaption></figure><p>Then select all items from the CTE1, where rank is 1, which gives the first item purchased by each customer; the answer to the question.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*ZLTNBaeJM8sD5jDeFikrvA.jpeg" /><figcaption>Output</figcaption></figure><p>According to the output, customer A purchased two items on his first visit.</p><p>#4: What is the most purchased item on the menu, and how many times was it purchased by all customers?</p><p>Counting the item purchased, grouping them by the product name, order by the count and limit 1 solves this question</p><pre>SELECT m.product_name, <br>       COUNT(s.product_id) AS num_of_purchase<br>FROM dannys_diner.sales s<br>JOIN dannys_diner.menu m<br> ON s.product_id = m.product_id<br>GROUP BY m.product_name<br>ORDER BY num_of_purchase DESC<br>LIMIT 1;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/1*qeMlw5EfJFBnrsU60Gye4w.jpeg" /></figure><p>Ramen was purchased 8 times and is the most purchased item on the menu</p><p>#5:<strong> Which item was the most popular for each customer?</strong></p><p>Here, using an aggregation, count, in the windows function we used in question 3 does the trick.</p><pre>WITH cte2 AS<br>(<br> SELECT s.customer_id,<br>      m.product_name,<br>   COUNT (s.product_id),<br>     RANK() OVER ( PARTITION BY s.customer_id ORDER BY COUNT(s.product_id)DESC) as rank<br> FROM dannys_diner.sales s<br> JOIN dannys_diner.menu m<br>  ON s.product_id = m.product_id<br> GROUP BY s.customer_id, m.product_name<br>)<br>SELECT *<br>FROM cte2<br>WHERE rank = 1</pre><p>Brief explanation: the solution uses a CTE that selects the customer_id, and the product name, takes the count of the sales, partitions them by the customer id, and orders them in descending order by the count as rank.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*nDjaHjIm4AQH7FQqW-jwhw.jpeg" /><figcaption>CTE output</figcaption></figure><p>Then selecting all items from the cte where rank = 1 gives the most popular item for each customer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*dn5OS-6dGTo0f4OUgEUnLw.jpeg" /><figcaption>Output</figcaption></figure><p>For customer B, the number of purchases for sushi, curry, and ramen is the same.</p><p>#6: <strong>Which item was purchased first by the customer after they became a member?</strong></p><p>Solving this question involves following a similar method we used in solving questions 3 and 5 but the trick here is the join.</p><pre>WITH cte AS<br>(<br> SELECT mb.customer_id, <br>        m.product_name, <br>        s.order_date, <br>        mb.join_date,<br>        RANK() OVER (PARTITION BY mb.customer_id ORDER BY s.order_date) AS rank<br> FROM dannys_diner.sales AS s<br> JOIN dannys_diner.menu AS m<br>  ON s.product_id = m.product_id<br> JOIN dannys_diner.members mb<br>  ON s.customer_id = mb.customer_id<br> WHERE s.order_date &gt;= mb.join_date<br>)<br>SELECT *<br>FROM cte<br>WHERE rank = 1</pre><p>Brief explanation: To answer this question, we joined three tables, the sales, menu, and member tables, where order_date is equal to or greater than the join_date. Below is the output of the cte</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*6D9-Jy4d032Ul_NMBBEfmA.jpeg" /><figcaption>CTE output</figcaption></figure><p>The CTE orders by the order date in ascending order and partitions by the customer id, so selecting all items where rank = 1 in the main query solves the question.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*VAkmU7F45nfBKEWRUNiuBg.jpeg" /><figcaption>output</figcaption></figure><p>Notice that customer C is not in the result. This is because customer C is not a member.</p><p>#7: <strong>Which item was purchased just before the customer became a member?</strong></p><p>The solution to this question follows the same logic as that of the previous question. The alternation is the where clause when joining the member table. It is joined to the sales table where the order date is less than the join date</p><pre>WITH cte as<br>(<br> SELECT  mb.customer_id, <br>         m.product_name, <br>         s.order_date, <br>         mb.join_date,<br>         RANK() OVER (PARTITION BY mb.customer_id ORDER BY s.order_date) AS rank<br> FROM dannys_diner.sales AS s<br> JOIN dannys_diner.menu AS m<br>  ON s.product_id = m.product_id<br> JOIN dannys_diner.members mb<br>  ON s.customer_id = mb.customer_id<br> WHERE s.order_date &lt; mb.join_date<br>)<br>SELECT *<br>FROM cte<br>WHERE rank = 1</pre><p>Below is the CTE output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*jwMp6oWanNE-8lGSgB6ksw.jpeg" /><figcaption>CTE output</figcaption></figure><p>Selecting all items from the cte where rank equals 1 solves the question</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*cqcEhbn3kLp3Kv56yOlf5g.jpeg" /></figure><p>Customer A bought two items, sushi and curry, just before becoming a member.</p><p>#8: <strong>What are the total items and amounts spent by each member before they became members?</strong></p><p>To solve this question, I did two aggregations, count and sum, in the select clause and grouped them by the customer_id</p><pre>SELECT mb.customer_id as member, <br>       COUNT (s.product_id) as total_item,<br>       SUM (m.price) as total_amount<br>FROM dannys_diner.sales s<br>JOIN dannys_diner.menu m<br> ON s.product_id = m.product_id<br>JOIN dannys_diner.members mb<br> ON s.customer_id =mb.customer_id<br>WHERE s.order_date &lt; mb.join_date<br>GROUP BY member</pre><p>Brief explanation: The three tables were joined together where order_date is less than the join date. Then the count of each product as total_item and the sum of the price as total amount were gotten and then grouped by the customer_id</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*xUQHv8KNkr0w2l7rBWi2cQ.jpeg" /><figcaption>Output</figcaption></figure><p>Customer B has purchased a total of 3 items and has spent a total of 40 usd</p><p>#9: <strong>If each $1 spent equates to 10 points and sushi has a 2x points multiplier — how many points would each customer have?</strong></p><p>The magic is performed by aggregation, sum, and a case statement that meets the condition in the question.</p><pre>SELECT s.customer_id as customer,<br>       SUM(CASE WHEN m.product_name = &#39;sushi&#39; THEN 2 * 10 * m.price ELSE 10 * m.price END) AS total_point<br>FROM dannys_diner.sales s <br>JOIN dannys_diner.menu m<br> ON s.product_id = m.product_id<br>GROUP BY customer_id<br>ORDER BY total_point DESC</pre><p>Brief explanation: The code above builds a case statements that returns 2 * 10 * price if the product is sushi and 10 * price if the product is not sushi, takes their sum as the total point, then groups by customer_id.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/284/1*x0e_LycmqyX90a4HJjHOQQ.jpeg" /></figure><p>Customer B has the highest point.</p><p>#10: <strong>In the first week after a customer joins the program (including their join date) they earn 2x points on all items, not just sushi <br> — how many points do customer A and B have at the end of January?</strong></p><p>In solving this question, I used a CTE and a case statement in the main query that returns the points based on the conditions that when the order date is between the join date and one week after the join date, then 2 * 10 * price point, when the order date is not between the join date and one week after the join date and the product is sushi, then 2 *10 * price, and else 10 * price point.</p><pre>WITH cte4 AS<br>(<br> SELECT s.customer_id as customer, <br>        m.product_name,<br>        m.price,<br>        mb.join_date,<br>        s.order_date<br> FROM dannys_diner.sales S<br> JOIN dannys_diner.menu m<br>  ON s.product_id = m.product_id<br> JOIN dannys_diner.members mb<br>  ON s.customer_id = mb.customer_id<br>)  <br>SELECT customer,<br>    SUM(CASE <br>   WHEN order_date &gt;= join_date AND order_date &lt;= join_date + interval &#39;1 week&#39; THEN 2 * 10 * price<br>   WHEN (order_date &lt; join_date AND order_date &gt; join_date + interval &#39;1 week&#39;) AND product_name = &#39;sushi&#39; THEN 2 * 10 * price<br>       ELSE 10 * price <br>  END) as total_point<br>FROM cte4<br>WHERE order_date &lt;= &#39;2021-01-31&#39;<br>GROUP BY customer<br>ORDER BY total_point DESC</pre><p>Brief explanation: The cte joins the three tables and selects the customer_id, product name, price, join date, and order date. The main query, selects the customer and builds a case statement that meets the condition: when the order date is between the join date and one week after the join date, then 2 * 10 * price point, when the order date is not between the join date and one week after the join date and the product is sushi, then 2 *10 * price, and else 10 * price point, where order date is less or eqaul to 2021–01–31 and groups by the customer</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/285/1*wDdyUN7gFS2BWaZtb107Iw.jpeg" /><figcaption>output</figcaption></figure><p>From the output, customer A has a higher total point of 1270 points</p><p>Thanks for reading…</p><p>I will appreciate your likes and comments.</p><p>Solutions to case study two are coming soon. See you.</p><p>Bye for now!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f5b5633784b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>