<?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 Esteban Mira on Medium]]></title>
        <description><![CDATA[Stories by Esteban Mira on Medium]]></description>
        <link>https://medium.com/@estebanmira099?source=rss-e0a43f8e7d91------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*A3KTFNzzcsqBTuaqd6qTow.jpeg</url>
            <title>Stories by Esteban Mira on Medium</title>
            <link>https://medium.com/@estebanmira099?source=rss-e0a43f8e7d91------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 19:32:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@estebanmira099/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[Magic in SQL]]></title>
            <link>https://medium.com/@estebanmira099/magic-in-sql-63d728c22d35?source=rss-e0a43f8e7d91------2</link>
            <guid isPermaLink="false">https://medium.com/p/63d728c22d35</guid>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Esteban Mira]]></dc:creator>
            <pubDate>Mon, 03 Feb 2025 12:57:24 GMT</pubDate>
            <atom:updated>2025-02-13T18:15:34.369Z</atom:updated>
            <content:encoded><![CDATA[<p>“Any sufficiently advanced technology is indistinguishable from magic.” Arthur C. Clarke</p><p>The first time I experienced magic, “real” magic, was when I started using a database. What usually took me more than an hour, I accomplished in less than five minutes.</p><p>The second time was when I learned to use dynamic dates and parameters.</p><p>I remember showing Mr. K my finalized bi-weekly performance report. Something like this just to keep everything simple.</p><pre>SELECT Employee<br>  , SUM(billed_services)<br> FROM Data_table<br> WHERE datebilled&gt;= &#39;2025-01-16&#39;<br>  AND datebilled&lt;&#39;2025-02-01&#39;<br>GROUP BY Employee</pre><p>He said something like, “Does that answer the questions you have?” I replied, “Yes, I can keep track of the performance and make adjustments.” He then suggested, “Why don’t you make the dates dynamic so you just need to run the full query without having to change the dates every time?” I was surprised and asked, “Wait… what?” He responded, “Yes, look into parameters!”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*XMvxavT7zLwaNcuFfSN6ww.jpeg" /><figcaption>Parameters…</figcaption></figure><p>And so, I set out to transform that query from hardcoded to automatically selecting the correct dates based on “today’s” date.</p><p>First, I needed to get the dates using formulas. GETDATE() will bring today’s date. If I run the query today, a day between the first and the 15th of the month, I will need to set up the date on the 16th of the last month and on the 1st of this month.</p><p>DATEFROMPARTS(year, month, day) will build a date from three different parts: year, month, and day. If I use GETDATE() on these three parts, I will get today’s date.</p><pre>DATEFROMPARTS(year(getdate), month(getdate), day(getdate))</pre><p>The start day has to be the 16th, the month has to be the actual month minus one, and the year has to be the year from the actual month minus one.</p><pre>DATEFROMPARTS(YEAR(DATEADD(MONTH, -1, GETDATE())), MONTH(DATEADD(MONTH, -1, GETDATE())), 16)</pre><p>Okay, I have a formula to set up the beginning of the report. The end of the report is going to be this month’s 1st, which is easy.</p><pre>DATEFROMPARTS(year(GETDATE()), month(GETDATE()), 1)</pre><p>Now, I will use parameters to dynamically include these values in my query:</p><p><strong><em>In SQL, a parameter is a placeholder in a query that allows you to pass values dynamically. These can be used to filter, sort, or modify the results based on the input provided.</em></strong></p><p><strong><em>When creating a procedure and declaring a parameter name, the parameter name must begin with a single @ character and must be unique in the scope of the procedure.</em></strong></p><p><strong><em>Parameters must be defined with a data type when they are declared in a </em></strong><strong><em>CREATE PROCEDURE statement. The data type of parameter determines the type and range of values that are accepted for the parameter when the procedure is called.</em></strong></p><pre>DECLARE @startdate date;<br>SET @startdate = DATEFROMPARTS(YEAR(DATEADD(MONTH, -1, GETDATE())), MONTH(DATEADD(MONTH, -1, GETDATE())), 16)<br>DECLARE @enddate date;<br>SET @enddate = DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()), 1);<br>--And I include @startdate and @enddate on my query:<br>SELECT Employee<br>  , SUM(billed_services)<br> FROM Data_table<br>  WHERE datebilled&gt;= @startdate<br>  AND datebilled&lt;@enddate<br>GROUP BY Employee</pre><p>I am on the right track — I solved the first part of the problem. What if, instead of being today, on the first fifteen days of the month, we are in the second two weeks of the month? In that <strong>CASE</strong>, the @startdate should be this month’s 1st, and @enddate should be this month’s 16th.</p><pre>@startdate = DATEFROMPARTS(year(GETDATE()), month(GETDATE()), 1)<br>@enddate= DATEFROMPARTS(year(GETDATE()), month(GETDATE()), 16)</pre><p>Therefore, I need to wrap these parameters in a CASE statement, so the query becomes truly dynamic using one formula or another.</p><pre>DECLARE @startdate date;<br>SET @startdate = CASE <br>    WHEN DAY(GETDATE()) &gt; 15 THEN DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()), 1)<br>    ELSE DATEFROMPARTS(YEAR(DATEADD(MONTH, -1, GETDATE())), MONTH(DATEADD(MONTH, -1, GETDATE())), 16)<br>END;<br><br>DECLARE @enddate date;<br>SET @enddate = CASE <br>    WHEN DAY(GETDATE()) &gt; 15 THEN DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()), 16)<br>    ELSE DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()), 1)<br>END;</pre><p>If I run everything together, I don’t need to change anything. This report will retrieve all the data from either the last two weeks of last month (if I run the query before the 16th of this month) or the first two weeks of this month (if I run the query after the 15th).</p><pre>DECLARE @startdate date;<br>SET @startdate = CASE <br>    WHEN DAY(GETDATE()) &gt; 15 THEN DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()), 1)<br>    ELSE DATEFROMPARTS(YEAR(DATEADD(MONTH, -1, GETDATE())), MONTH(DATEADD(MONTH, -1, GETDATE())), 16)<br>END;<br><br>DECLARE @enddate date;<br>SET @enddate = CASE <br>    WHEN DAY(GETDATE()) &gt; 15 THEN DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()), 16)<br>    ELSE DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()), 1)<br>END;<br><br>SELECT Employee<br>  , SUM(billed_services)<br> FROM Data_table<br> WHERE datebilled&gt;= @startdate<br>  AND datebilled&lt;@enddate<br>GROUP BY Employee</pre><p>It is not magic, but my report is alive now</p><p>“IT’S ALIVE! IT’S ALIVE! IT’S ALIVE! IT’S ALIVE! Oh, in the name of God! Now I know what it feels like to be God!”</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F-Ca-2FRsTx8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D-Ca-2FRsTx8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F-Ca-2FRsTx8%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d5e23b8866c8428a4b3d8ce61dfdb47/href">https://medium.com/media/9d5e23b8866c8428a4b3d8ce61dfdb47/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63d728c22d35" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Performance Dashboard V.2]]></title>
            <link>https://medium.com/@estebanmira099/performance-dashboard-v-2-4c9092a4fa8b?source=rss-e0a43f8e7d91------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c9092a4fa8b</guid>
            <dc:creator><![CDATA[Esteban Mira]]></dc:creator>
            <pubDate>Mon, 27 Jan 2025 11:46:47 GMT</pubDate>
            <atom:updated>2025-01-27T11:46:47.989Z</atom:updated>
            <content:encoded><![CDATA[<p>The primary goal of my data analysis was to track the performance of my employees, including key performance indicators such as starting time, hourly rate, etc. Without any existing tools, I took it upon myself to learn and develop these tools. Along the way, I discovered that these same tools could be used to create other valuable reports and tools to help grow and improve my organization. For example, I developed a weekly check for double billing, customer tracking, and route optimization.</p><p>I found that tracking my employees’ performance was <a href="https://medium.com/@estebanmira099/performance-dashboard-from-sql-to-excel-to-tableau-b4ce0c3e1272">straightforward</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EAVRhOXYWhQY4uAfhrjdrQ.png" /></figure><p>Instead of focusing solely on how much each employee was billing, I looked at the billing per customer (spaceship dealer), the number of units, and used simple math to set up a minimum number of visits per week.</p><p>I decided to use the Story feature on <a href="https://public.tableau.com/app/profile/esteban.mira7247/viz/Performancemonitortotalv_2/Story1">Tableau </a>to generate these two perspectives. On one side, we have already seen employee performance, and on the other side, I will show you a sneak peek of customer performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6-DpgzshY5_DuGj6miHjrg.png" /></figure><p>We have the monthly billing per spaceship dealer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*euDDkYpg52fAmbKfJMhx-Q.png" /></figure><p>The monthly spaceships processed per spaceship dealer</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*ZVTDSGUMW07zA-ai63OtQA.png" /></figure><p>And the recommended minimum number of visits per spaceship dealer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*rQKSMs7M5TQajiSCIxcsdA.png" /></figure><p>Keep in mind that this is only an estimate. To set up a route, there are more variables to consider, such as customer needs and geographical location. However, it is useful to keep in mind how many visits we can make to a customer, ensuring all of them are worthwhile.</p><p>This is only a sneak peek. In a finished dashboard, I would include historical data with variability to add another indicator of changes in workload. For now, I will keep that data to myself.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c9092a4fa8b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Performance Dashboard: From SQL, to Excel, to Tableau]]></title>
            <link>https://medium.com/@estebanmira099/performance-dashboard-from-sql-to-excel-to-tableau-b4ce0c3e1272?source=rss-e0a43f8e7d91------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4ce0c3e1272</guid>
            <dc:creator><![CDATA[Esteban Mira]]></dc:creator>
            <pubDate>Sat, 18 Jan 2025 22:23:03 GMT</pubDate>
            <atom:updated>2025-01-18T22:23:03.086Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OugN02WNV6UptFEGND8h_A.png" /></figure><p>Tableau Public <a href="https://public.tableau.com/app/profile/esteban.mira7247/vizzes">here</a></p><h3>Introduction</h3><p>The more I learn, the more I realize how much I don’t know.</p><p>While I primarily use SQL and Excel at work to meet all our organizational data analysis needs, I’ve been exploring Tableau as part of my professional growth. Inspired by my previous post; <a href="https://medium.com/@estebanmira099/and-i-started-analyzing-data-f7b30d58b9b5">And I started analyzing data</a>, I set out to create a dashboard to display a monthly employee performance report.</p><p>Learning Tableau through tutorials and courses seemed straightforward — until I started applying it to a real-world scenario. That’s when the challenges grew exponentially, but overcoming them proved rewarding.</p><p>For this project, I used SQL, Excel, and finally Tableau to transform raw data into a comprehensive performance dashboard. Here’s the process I followed:</p><h3>SQL: Data Extraction</h3><p>I imported and filtered the required data from the database, selecting a random month to demonstrate how a dashboard could look in Tableau.</p><p>To design the dashboard effectively, I needed data from:</p><ul><li>The selected month</li><li>The previous month</li><li>The same month in the previous year</li></ul><p>This approach ensures a holistic view of performance trends.</p><h3>Excel: Data Cleaning and Transformation</h3><p>Once the data was imported into Excel, I adjusted data types, cleaned the dataset, and applied transformations using functions like XLOOKUP. To maintain confidentiality, I replaced employee names, dealerships, and billing amounts with anonymized values. For a performance dashboard, the exact figures are less important than the structure and insights.</p><h3>Tableau: Building the Dashboard</h3><p>I connected the cleaned data to Tableau and began creating the dashboard. Key panels include:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OugN02WNV6UptFEGND8h_A.png" /></figure><ol><li><strong>Monthly Billing Overview</strong>: Comparing the selected month with the previous month and the same month last year (Year-to-Year Comparison).</li><li><strong>Employee Performance Analysis</strong>: Highlighting high performers and underperformers using calculated fields and conditional formatting (e.g., red flags for underperformance).</li><li><strong>Dealership Contributions</strong>: A breakdown of billing by dealership to assess regional or client-based performance.</li><li><strong>Monthly report and Granular Daily Performance</strong>: A detailed chart showing daily start times, billed amounts, hours worked, and more. This chart links back to the monthly report as a filter for deeper analysis.</li></ol><h3>Key Insights from the Dashboard</h3><h4>1) General Data Analysis</h4><p>The overall billed amount for the selected month is positive, with no immediate red flags in the high-level trends. Improving the previous month performance and same month last year performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*USLRdn7NxxCgKcXK-kjRBQ.png" /></figure><h4>2) Employee Performance</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hpMoRB7NrorYSxkyvrp19A.png" /></figure><p><strong>High Performers</strong>:</p><ul><li><strong>Ovi Juan</strong> and <strong>Eldara Valis</strong> exceeded $12,000 in billing. This exceptional performance warrants either a bonus or public recognition.</li></ul><p><strong>Underperformers</strong>:</p><ul><li><strong>DB Bear</strong>: Billed only $1,334. Upon analysis, it’s evident he is in training and worked just seven days. His performance is expected.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GIEC8_mCuLDHXP4zITVi8g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jQYdVBS83N-JRatFTp_k4A.png" /></figure><ul><li><strong>Luke Skydancer</strong>, <strong>Darth Kyran</strong>, and <strong>Lando D</strong>: Working part-time with limited dealership routes. Assigning more clients could enhance their productivity.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*11bdaRzEMwmkqmOiYCrCWg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qvUdtqKwG7JXljW8i8jJGA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hJLOxTk-XpEGqHir6DeR5Q.png" /></figure><ul><li><strong>Torin Zalar</strong>: Underperforming despite visiting enough dealerships. While his earnings per hour ($23/h) are reasonable, he is working fewer hours than expected. Further investigation reveals inconsistent daily performance, with only one day exceeding 8 hours and many below the daily minimum.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QN2_cC0W___68Pb7yAP80g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iodYYfnxO7RxNAggR77pHw.png" /></figure><h4>3) Monthly Report Highlights</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a6uma8eCZh5BUiOTvQO_mQ.png" /></figure><ul><li><strong>Ovi Juan</strong>: While highly productive, Ovi Juan consistently works over 8 hours daily, which could lead to burnout. Additionally, his efficiency ($21/h) is below optimal. A review of his schedule and processes is recommended to improve efficiency.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hSmDi8BdhzDZy_HAT7YyTg.png" /></figure><ul><li><strong>Anak Rogue</strong>: Despite being a solid performer, Anak’s efficiency is below $20/h. A review of his processes and potential retraining may help improve his output.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qarTr3sw3pBJv2Xi-BqQ5A.png" /></figure><h3>Conclusions</h3><ul><li>Overall, monthly billing has improved.</li><li>Two employees demonstrated exceptional performance and deserve recognition or rewards.</li><li>One employee is in training, and three part-time workers could handle additional workload.</li><li>One employee is underperforming and requires targeted intervention to increase hours and productivity.</li><li>Two good employees could improve efficiency through process optimization and possible retraining.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4ce0c3e1272" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Practicing Tableau]]></title>
            <link>https://medium.com/@estebanmira099/practicing-tableau-1d3639e75a8e?source=rss-e0a43f8e7d91------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d3639e75a8e</guid>
            <dc:creator><![CDATA[Esteban Mira]]></dc:creator>
            <pubDate>Mon, 09 Dec 2024 13:36:47 GMT</pubDate>
            <atom:updated>2024-12-09T13:41:10.969Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*okUEaopY0SOHKhgnThA3UA.png" /><figcaption><a href="https://public.tableau.com/views/discountmart_17337507602990/Dashboard1?:language=en-US&amp;:sid=&amp;:redirect=auth&amp;:display_count=n&amp;:origin=viz_share_link">https://public.tableau.com/views/discountmart_17337507602990/Dashboard1?:language=en-US&amp;:sid=&amp;:redirect=auth&amp;:display_count=n&amp;:origin=viz_share_link</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d3639e75a8e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Round 2. Adventure Works Sales Analysis]]></title>
            <link>https://medium.com/@estebanmira099/round-2-adventure-works-sales-analysis-4d45cc22fb5b?source=rss-e0a43f8e7d91------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d45cc22fb5b</guid>
            <dc:creator><![CDATA[Esteban Mira]]></dc:creator>
            <pubDate>Mon, 04 Nov 2024 11:01:02 GMT</pubDate>
            <atom:updated>2024-11-04T11:01:02.883Z</atom:updated>
            <content:encoded><![CDATA[<p>In this second round I am going to break down the sales analysis over time in the different territories, highlighting from differences and similarities.</p><p><strong>Selection and data filtering in SQL;</strong></p><p>My first step is to filter the data by territory and calculate each territory’s z-score. This will help determine if territories can be reasonably compared against each other. One of them, as we’ll see, is an outlier.</p><pre>WITH data_table AS (<br>    SELECT <br>        SOH.TerritoryID AS Territory_ID, <br>        ST.Name AS TerritoryName, <br>        SUM(SOH.SubTotal) AS total_sum<br>    FROM <br>        [adventure].[Sales].[SalesOrderHeader] SOH<br>    INNER JOIN <br>        Sales.SalesTerritory ST ON SOH.TerritoryID = ST.TerritoryID<br>    GROUP BY <br>        SOH.TerritoryID, ST.Name<br>), <br>stats AS (<br>    SELECT <br>        AVG(total_sum) AS mean_total,<br>        STDEV(total_sum) AS stddev_total<br>    FROM <br>        data_table<br><br>),<br>normalized_data AS (<br>    SELECT <br>        Territory_ID,<br>        TerritoryName,<br>        total_sum,<br>        (total_sum - stats.mean_total) / stats.stddev_total AS z_score<br>    FROM <br>        data_table, stats<br>)<br>SELECT <br>    Territory_ID,<br>    TerritoryName,<br>    total_sum,<br>    z_score,<br>    CASE<br>        WHEN ABS(z_score) &lt;= 1.96 THEN &#39;Normal&#39;<br>        ELSE &#39;Not Normal&#39;<br>    END AS normality<br>FROM <br>    normalized_data<br>ORDER BY <br>    Territory_ID;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*pOFAopouwAPn82bjlKriEA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*rgrTdyXHOhreAss06fdC_w.png" /></figure><p>After calculating the standard deviation, it becomes clear that only one territory — the Southwest — is an outlier, while all others fall within the normal range. Due to this distinction, I’ll conduct the analysis in two parts: one for the territories that meet normality criteria and a separate one for the outlier.</p><pre><br>WITH BaseData AS (<br> SELECT FORMAT(SOH.OrderDate, &#39;yyyy-MM&#39;) AS Year_Month<br> , SUM(SOH.TotalDue) as Total_Due<br> , SOH.TerritoryID<br> , ST.Name as TerritoryName<br> FROM [adventure].[Sales].[SalesOrderHeader] SOH<br>    INNER JOIN <br>        Sales.SalesTerritory ST <br>   ON SOH.TerritoryID = ST.TerritoryID<br>GROUP BY FORMAT(OrderDate, &#39;yyyy-MM&#39;)<br>  , SOH.TerritoryID<br>  , ST.Name<br>)<br>SELECT TerritoryID <br> , TerritoryName<br> , Year_Month<br> , Total_Due<br> , AVG(Total_Due) OVER (ORDER BY Year_Month ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS RollingAverage<br>FROM BaseData<br>ORDER BY Year_Month ASC</pre><p>Dumping the filtered month to month sales data on Excel I can start generating tables and charts to understand better the reality of the sales.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*woMfhlatt0DuITC1doTRfw.png" /></figure><p><strong>Central, Northeast, and Southeast</strong></p><p>Among the “normal” territories the first thing that catches my attention is we have some missing values:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TWS2pMOJBgLT3gxyReLFWQ.png" /></figure><p>Central, Northeast, and Southeast in September, October, and November of 2011, as well as in February 2014. These missing values could be estimated using data from surrounding months, or by applying the mean or median, but any imputation would introduce some degree of assumption.</p><p>And if I use other territories with similar total sales, we can see the month to month performance is radically different:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s8N8me63toqGZXw7f2cddQ.png" /></figure><p>For instance, France and the United Kingdom only begin to resemble Central, Northeast, and Southeast in April and May of 2012, while Germany’s performance aligns closer to these peers starting in May 2013. Therefore, using other territories to fill missing data could lead to considerable errors in the analysis.</p><p>Overall with the data I have I can point that these three territories are selling the least consistently. There is some volatility that could indicate seasonal patterns or promotional periods. These territories have an overall overtime grow but visually it’s practically not perceptible’</p><p><strong>France, Germany, UK</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LuiJzgM11_hdbjl6Sy4Oag.png" /></figure><p>For France, Germany, and the United Kingdom, there is a distinct shift in sales before and after May 2013. Before this period, sales are lower but relatively stable; however, starting in May 2013, there is a substantial increase in total sales accompanied by greater volatility between months.</p><p>The average total sales for these three territories in 2012–04 is 49,268 and jumps to 115,700 in 2012–05. Later on the average sales in April, May and June 2013 made another significant jump: 146,016–231,110–566,205.</p><p><strong>Australia, Canada, Northwest</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n1JQfJWtX0agLvk_XWlvHA.png" /></figure><p>Australia, Canada, and Northwest are the top performers among the ‘normal’ territories, showing steady growth over time. Australia, in particular, has minimal fluctuations, indicating a stable market. In contrast, Canada and Northwest experience similar swings to other territories, but they outperform in sales during the first two years.</p><p>Outlier; Southwest</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B1iggsbyrNcIqJQZb64L6Q.png" /></figure><p>Southwest stands out as an outlier, with a z-score of +2.19, reflecting consistently higher sales than all other territories. Although its sales profile shares some characteristics with other territories — such as swings, seasonal peaks, and year-over-year growth — the Southwest territory surpasses all others in nearly every month.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*4ms0URpBOZEAeHjC86bsLA.png" /></figure><p><strong>Conclusions</strong></p><ul><li>There is missing data on Central, Southeast, and Northeast. We can’t fill the data with averages, mean, median due to the overall volatility of sales. And we can’t fill the data using other territories due to big discrepancies on performance.</li><li>France, Germany and UK experiment a fast increase in sales, accompanied of a huge increase in swings and volatility. It could be due to season effects (before summer, end summer, holiday season). It should be looked to mitigate the low points on these swings.</li><li>Australia, Canada and Northwest Territories are the best performers making the difference on the first two years of the data where they outperform all the other territories</li><li>The difference in performance between first two years and the last year, as well the over perform of Southwest need more deep analysis like compare different territorial promotions, number of salesmen, different products, etc…</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d45cc22fb5b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adventure Works Sales analysis]]></title>
            <link>https://medium.com/@estebanmira099/adventure-works-sales-analysis-39fd5942968d?source=rss-e0a43f8e7d91------2</link>
            <guid isPermaLink="false">https://medium.com/p/39fd5942968d</guid>
            <dc:creator><![CDATA[Esteban Mira]]></dc:creator>
            <pubDate>Mon, 21 Oct 2024 11:01:42 GMT</pubDate>
            <atom:updated>2024-10-21T12:32:32.485Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction</strong></p><p>As part of my SQL learning journey, I’ve been working on a self-designed database where I control all the data input. While this simplifies things, I wanted to test my skills with a dataset beyond my control. Enter the AdventureWorks database, where I aim to create a comprehensive sales report using SQL Server Management Studio and Excel. This project is structured into three phases: general sales analysis, granular regional/store analysis, and salesperson analysis.</p><p><strong>Round 1, General Sales Analysis</strong></p><p>To do this analysis I will work with the table Sales.SalesOrderHeader. These are all the columns:</p><blockquote>[SalesOrderID], [RevisionNumber], [<strong>OrderDate</strong>], [DueDate], [ShipDate], [Status], [OnlineOrderFlag], [SalesOrderNumber], [PurchaseOrderNumber], [AccountNumber], [<strong>CustomerID</strong>], [<strong>SalesPersonID</strong>], [<strong>TerritoryID</strong>], [BillToAddressID], [ShipToAddressID], [ShipMethodID], [CreditCardID], [CreditCardApprovalCode], [CurrencyRateID], [SubTotal] ,[TaxAmt] , [Freight], [<strong>TotalDue</strong>], [Comment], [rowguid], [ModifiedDate]</blockquote><p>There is plenty of information I can extract only using OrderDate, and TotalDue. Also I see some names of other columns that will be very useful later on, like CustomerID, SalesPersonID, TerritoryID, these columns are referencing other tables.</p><ul><li>Check for duplicate rows</li></ul><pre>SELECT <br>  count(*) <br>FROM <br>  [adventure].[Sales].[SalesOrderHeader] <br>GROUP BY <br>  [SalesOrderID] <br>HAVING <br>  COUNT(*)&gt; 1</pre><p>This query confirmed there are no duplicate rows, so we can proceed with the analysis.</p><ul><li>Sales month to month, including the monthly average</li></ul><pre>SELECT FORMAT(OrderDate, &#39;yyyy-MM&#39;) AS Year_Month<br> , SUM(TotalDue) as Total_Due<br> , AVG(SUM(TotalDue)) OVER() AS Avg_Total_Due<br>FROM Sales.SalesOrderHeader<br>GROUP BY FORMAT(OrderDate, &#39;yyyy-MM&#39;SELECT FORMAT(OrderDate, &#39;yyyy-MM&#39;) AS Year_Month<br>, SUM(TotalDue) as Total_Due<br>FROM Sales.SalesOrderHeader<br>GROUP BY FORMAT(OrderDate, &#39;yyyy-MM&#39;)<br>ORDER BY FORMAT(OrderDate, &#39;yyyy-MM&#39;)</pre><p>Before throwing it into excel, I am using this table as CTE making some changes to make easier the work using excel, and adding more calculations using SQL: Rolling average of the last 3 months, percentage of change month to month, avg total due and Standard Deviation</p><pre><br>WITH BaseData AS (<br> SELECT FORMAT(OrderDate, &#39;yyyy-MM&#39;) AS Year_Month<br> , SUM(TotalDue) as Total_Due<br> , AVG(SUM(TotalDue)) OVER() AS Avg_Total_Due<br>FROM Sales.SalesOrderHeader<br>GROUP BY FORMAT(OrderDate, &#39;yyyy-MM&#39;)<br><br>)<br><br>SELECT Year_Month<br> , LEFT(Year_Month, 4) as Year<br> , Right(Year_Month, 2) as Month<br> , Total_Due<br> , AVG(Total_Due) OVER (ORDER BY Year_Month ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS RollingAverage<br>-- , LAG(total_due, 1) OVER (ORDER BY Year_Month) AS previous_total_due<br> , CONCAT(ROUND(100.0 * (CAST(total_due AS FLOAT) - CAST(LAG(total_due, 1) OVER (ORDER BY Year_Month) AS FLOAT)) / <br>                  CAST(LAG(total_due, 1) OVER (ORDER BY Year_Month) AS FLOAT), 2), &#39;%&#39;) AS PercChangeMonToMonth<br> , Avg_Total_Due <br> , STDEV(Total_Due) OVER () AS StdDev_Total_Due<br>FROM BaseData<br>ORDER BY Year_Month ASC</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*Nb9dNXQJKN6fCBfaJzWfCw.png" /></figure><p>The average Total Due is 3,242,547.00, with a standard deviation of 1,787,700.91, indicating a 55% variability. 55% variability, or coefficient of variation, is quite significant for a global company’s sales. It indicates a high degree of fluctuation in TotalDue from month to month, which could suggest instability or inconsistency in revenue streams.</p><p>This level of volatility might warrant a deeper analysis into the causes, such as seasonal demand, market conditions, promotional activities, or other external factors. As well a more granular analysis checking the different Territory Areas</p><p>Now I have all the data I need to generate charts and drive insights using Excel. I start with the sum total and the rolling average to have a clear view of the evolution of sales.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*QjG1qD1y3O7OfP7KrrZZdQ.png" /></figure><p>In this chart, the most noticeable feature is the high variability in total due, with significant fluctuations that make it difficult to draw insights. However, the trend line reveals a steady growth in sales over time. Also using the rolling average smooths the drastic fluctuations giving us some kind of seasonality seeing how the sales grow more in summer (June and July).</p><p>The next step is to pivot this chart to compare the lines of every year month to month:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*oFa5OUBKG0D5EX9I1oDEow.png" /></figure><p>With this chart comparing month to month I”d like to say there are two clear seasonal patterns where the sales grow, but all the data from first, and the last months of the chart (year 2011 and 2014) add noise to the overall trend, so I am gonna filter out those two years and see what I get.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*fvGl3MGjbkE4z52rc7I2BQ.png" /></figure><p>Now we have a clear pattern of growing sales on “summer” months (June, July), upturn in September, and also in December. This suggests seasonality during the summer months and the holiday season. It would be beneficial to correlate these findings with marketing campaigns or other departmental activities to identify potential drivers behind these patterns.</p><p><strong>Insights AdventureWorks general sales analysis:</strong></p><ol><li><strong>Sales Growth Over Time</strong>: Despite high variability in monthly sales (Total Due), a trend of steady growth is observed, especially after smoothing the data with a rolling average. The general trend shows that sales increase steadily over the years, with some months performing consistently better than others.</li><li><strong>Seasonality Patterns</strong>: Filtering out the noise from the first and last years (2011 and 2014), there is a clear seasonality in sales. There are noticeable spikes in the summer months (June, July), as well as in September and December. This suggests higher sales during the summer and holiday seasons, potentially aligning with demand increases or promotional activities.</li><li><strong>High Variability</strong>: A coefficient of variation of 55% shows substantial fluctuation in monthly sales, indicating instability. This could be due to various factors such as seasonal demand, economic conditions, or internal activities like marketing campaigns.</li><li><strong>Further Analysis Recommendations</strong>:</li></ol><ul><li><strong>Investigating anomalies</strong>: Sharp changes in specific months, such as March and June 2014, need to be explored to understand their causes.</li><li><strong>Correlating external factors</strong>: Examining possible external influences (market conditions, business cycles) or internal actions (campaigns, policy changes) could provide context for sales volatility.</li><li><strong>Segmenting data</strong>: A more granular analysis by region or product category might reveal whether certain areas or products are driving these fluctuations.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39fd5942968d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL Toolbox]]></title>
            <link>https://medium.com/@estebanmira099/sql-toolbox-7993ef3a211f?source=rss-e0a43f8e7d91------2</link>
            <guid isPermaLink="false">https://medium.com/p/7993ef3a211f</guid>
            <category><![CDATA[sql-for-data-analysis]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[sql-server]]></category>
            <category><![CDATA[sql-functions]]></category>
            <category><![CDATA[sql-for-beginners]]></category>
            <dc:creator><![CDATA[Esteban Mira]]></dc:creator>
            <pubDate>Mon, 14 Oct 2024 13:02:19 GMT</pubDate>
            <atom:updated>2024-10-14T13:02:19.253Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>SELECT: Statement to retrieve data from a database.</em></blockquote><blockquote><em>FROM: Clause, that specifies the table from witch to retrieve or manipulate data.</em></blockquote><blockquote><em>WHERE: Clause to filter records that meet specific conditions.</em></blockquote><blockquote><em>GROUP BY : Clause, groups rows that have the same values in specified columns.</em></blockquote><blockquote><em>SUM(): Function</em><strong><em>, </em></strong><em>aggregates numeric data.</em></blockquote><blockquote>CONVERT(TIME, timestamp) converts the timestamp to a time format.</blockquote><blockquote>MIN(CONVERT(TIME, timestamp)) finds the earliest (minimum value) time.</blockquote><blockquote>DATEADD (MINUTE, -30, MIN(CONVERT(TIME, timestamp))) subtracts 30 minutes from this earliest time.</blockquote><blockquote>CONVERT(VARCHAR(5), ..., 108) formats this time as a string in hh:mm format.</blockquote><blockquote>DATEDIFF(HOUR, MIN(Timestamp), MAX(Timestamp)) calculates the difference in hours between the earliest and latest timestamps.</blockquote><blockquote>CAST(Timestamp as Date) to truncate the timestamp to just the date part, ignoring the time.</blockquote><blockquote><em>LIKE &#39;%XXX’</em> “Like“ will match any string within the quotes, using % wildcard retrieves any value that finishes with XXX</blockquote><blockquote><em>CREATE TABLE()</em> Creates a table within the data base wit the columns inside the parenthesis. Every column has the name and the type of data.</blockquote><blockquote>DATETIME data type is used to store date and time information together, in the format YYYY-MM-DD HH:MI:SS</blockquote><blockquote>PRIMARY KEY: This constraint ensures that each value in the EmployeeID column is unique and not null, making it the primary key of the table.</blockquote><blockquote>FOREIGN KEY (VehicleID)a constraint that ensures any value entered in the VehicleID column of the Services_Table must already exist in the VehicleID column of the spaceshipTable.</blockquote><blockquote><em>NVARCHAR</em> is a data type in SQL used to store variable-length Unicode character data, with the length in parenthesis (50)</blockquote><blockquote>INSERT INTO populates the given table with the selection from other tables like raw_data_table (rd).</blockquote><blockquote>CHARINDEX(&#39; &#39;, rd.Employee) &gt; 0 Check if there is a space character in the Employee field. And CASE to extract the first name: <strong>If True</strong>:SUBSTRING(rd.Employee, 1, CHARINDEX(&#39; &#39;, rd.Employee) -1): Extracts the substring from the start of Employee up to (but not including) the first space.</blockquote><blockquote><strong>If False</strong>:rd.Employee: Uses the entire Employee field as the first name (if there is no space).</blockquote><blockquote>And a similar query to get the last name <em>SUBSTRING(rd.Employee, 1, CHARINDEX(&#39; &#39;, rd.Employee) +1)</em></blockquote><blockquote>Joins with phone_book_table (cg) to get email and phone information.</blockquote><blockquote>DECLARE <a href="http://twitter.com/startdate">@startdate</a> datetime2This declares a variable <a href="http://twitter.com/startdate">@startdate</a> of type datetime2</blockquote><blockquote>GETDATE(): Gets the current date and time</blockquote><blockquote>YEAR(GETDATE()) AND MONTH(GETDATE(): Extracts the year and month from the current date.</blockquote><blockquote>DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()), 1): Creates a date using the extracted year and month, and sets the day to 1.</blockquote><blockquote>DATEADD(MONTH, -1, …): Subtracts one month from the date create, resulting in the first day of the previous month.</blockquote><blockquote>MIN(CONVERT(TIME, st.Timestamp_Created)): Converts the Timestamp_Created to just the time part and finds the minimum time value.</blockquote><blockquote>DATEADD(MINUTE, -30, ...): Subtracts 30 minutes from the minimum time value.</blockquote><blockquote>CONVERT(VARCHAR(5), ..., 108): Converts the resulting time to a string in the format HH:MI (24-hour format)</blockquote><blockquote>DATEDIFF(HOUR, MIN(st.Timestamp_Created), MAX(st.Timestamp_Created)) + 1 as TotalHours</blockquote><blockquote>MIN(st.Timestamp_Created): Finds the earliest timestamp.</blockquote><blockquote>MAX(st.Timestamp_Created): Finds the latest timestamp.</blockquote><blockquote>DATEDIFF(HOUR, ..., ...): Calculates the difference in hours between the earliest and latest timestamps.</blockquote><blockquote>CAST(st.Timestamp_Created as Date): Converts the Timestamp_Created to just the date part, removing the time component.</blockquote><blockquote>And by grouping everything by TruncatedDated, all these values will be showed by day</blockquote><blockquote>SUM(TotalHours) / 2 AS HoursperWeek: Sums the TotalHours and divides by 2 to calculate the average hours per week, assuming a two-week period.</blockquote><blockquote>SUM(TotalBilledbyDay) * 0.X as AproxComision: Calculates the approximate commission by multiplying the total billed amount by a commission rate (represented by 0.X)</blockquote><blockquote>(SUM(TotalBilledbyDay) / SUM(TotalHours)) * 0.X as RatioMoneyperHour: Calculates the ratio of money earned per hour by dividing the total billed amount by the total hours and multiplying by a factor (represented by 0.X).</blockquote><blockquote>CONVERT(VARCHAR(5), MIN(StartingTime), 108) AS EarliestDay: Converts the earliest starting time to a string in the format HH:MI (24-hour format).</blockquote><blockquote>CONVERT(VARCHAR(5), MAX(StartingTime), 108) AS LatestDay: Converts the latest starting time to a string in the format HH:MI (24-hour format)</blockquote><blockquote>GROUP BY Employee Groups the results by the Employee column to perform the aggregations for each employee</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7993ef3a211f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[And I started analyzing data]]></title>
            <link>https://medium.com/@estebanmira099/and-i-started-analyzing-data-f7b30d58b9b5?source=rss-e0a43f8e7d91------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7b30d58b9b5</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Esteban Mira]]></dc:creator>
            <pubDate>Wed, 02 Oct 2024 02:07:14 GMT</pubDate>
            <atom:updated>2024-10-02T02:07:14.255Z</atom:updated>
            <content:encoded><![CDATA[<p>A long time ago — two years, in a galaxy far, far away — Denver, there were spaceship dealerships in need of help with data and various services. That’s how I began doing data analysis.</p><p>As a mid-level manager at a small company (5–10 employees), I quickly realized that I was spending 20% of my time on quality control and market research, while 70% was dedicated to “firefighting” — directly solving customer issues. Whether I was working at a strategic level (10,000 ft) or dealing with ground-level crises (0 ft), I spent the remaining 10% managing a team of field agents.</p><p>It became clear that asking “How are you doing?” or “How is everything?” didn’t give me the real story. Employees would say things were “good,” only for me to discover weeks later that some were quitting, or worse, a customer was canceling their services. I needed a better way to keep track of what was really happening, and the answer was data — raw data.</p><p>First step</p><p>I began learning basic SQL and set up a database on my computer. I was able to export raw data, including itemized services with timestamps, dollar amounts, employee names, and customer details. Using SQL Server Management Studio, I imported this CSV file as a flat file. After adjusting a few data types, the process became relatively straightforward.</p><pre>SELECT Employee<br>  , SUM($)<br>FROM raw_data_table<br>WHERE timestamp &gt; = first_day_of_last_month<br>  AND timestamp&lt; first_day_of_this_month<br>GROUP BY Employee</pre><blockquote><strong>SQL Personal Toolbox</strong></blockquote><blockquote>SELECT: Statement to retrieve data from a database.</blockquote><blockquote>FROM: Clause, that specifies the table from witch to retrieve or manipulate data.</blockquote><blockquote>WHERE: Clause to filter records that meet specific conditions.</blockquote><blockquote>GROUP BY : Clause, groups rows that have the same values in specified columns.</blockquote><blockquote>SUM(): Function<strong>, </strong>aggregates numeric data.</blockquote><p>With this query, I could check how much money every employee was billing without waiting for accounting or manually going through the bills. I felt a disturbance in the Force…</p><p>Digging Deeper</p><p>The values I obtained weren’t 100% accurate, but they gave me enough inside to monitor performance. But, I needed to track performance more frequently and in greater detail than once a month. I decided that two-week intervals would provide enough day-to-day data to spot trends and suggest improvements.</p><p>I created a simple query that provided all the information I needed: employee name, the first daily timestamp (which I adjusted by adding 30 minutes to approximate their actual start time), and the last daily timestamp. By subtracting the two, I could calculate how many hours each employee worked in the field. I added an extra hour per day to account for driving time and other variables, and I also tracked the date and the total billing of the day.</p><pre>SELECT Employee<br>, CONVERT(VARCHAR(5), DATEADD(MINUTE, -30, MIN(CONVERT(TIME, timestamp))), 108) as StartingTime<br>, DATEDIFF(HOUR, MIN(Timestamp), MAX(Timestamp)) +1 as TotalHours<br>, CAST(Timestamp as Date) AS TruncatedDate<br>, SUM($) as TotalBilledbyDay<br>FROM raw_data_table<br>WHERE Timestamp &gt;= first_day_of_last_month<br>and Timestamp&lt; first_day_of_current_month<br>GROUP BY Employee, CAST(Timestamp AS DATE)<br>ORDER BY TruncatedDate ASC</pre><blockquote><strong>SQL Personal Toolbox</strong></blockquote><blockquote>CONVERT(TIME, timestamp) converts the timestamp to a time format.</blockquote><blockquote>MIN(CONVERT(TIME, timestamp)) finds the earliest (minimum value) time.</blockquote><blockquote>DATEADD (MINUTE, -30, MIN(CONVERT(TIME, timestamp))) subtracts 30 minutes from this earliest time.</blockquote><blockquote>CONVERT(VARCHAR(5), ..., 108) formats this time as a string in hh:mm format.</blockquote><blockquote>DATEDIFF(HOUR, MIN(Timestamp), MAX(Timestamp)) calculates the difference in hours between the earliest and latest timestamps.</blockquote><blockquote>CAST(Timestamp as Date) to truncate the timestamp to just the date part, ignoring the time.</blockquote><p>Now I had powers! I could see how much money my employees were billing (to check if they were truly doing “good”), how many hours they were working, and when they were starting their shifts, enabling me to make adjustments. I could also identify who might need help and who could handle more workload. This data-driven approach not only improved employee retention but also boosted performance, and increase in customer satisfaction.</p><p>Around that same time, I received a call from a customer requesting all the data and services for one spaceship that had been serviced over a year prior. In the past, I would have spent hours sifting through invoices to find the specific frame number. This time, it took me five minutes (after restarting my computer).</p><pre>SELECT * FROM raw_data_table<br>WHERE BAST LIKE &#39;%XXXX&#39;</pre><blockquote><strong>SQL Personal Toolbox</strong></blockquote><blockquote><em>LIKE &#39;%XXX’</em> “Like“ will match any string within the quotes, using % wildcard retrieves any value that finishes with XXX</blockquote><p>Normalization</p><p>I wanted more. I kept learning and found a group on the HoloNet where I could share my experiences and seek guidance. I found a Master who, after reviewing my queries, pointed with scorn: “One table? Small discrepancies? That’s a shame! Look into normalization!” I felt humiliated! (Not really — he explained the concept of table normalization, showed me the way, and helped me continue learning). He ignited something inside me.</p><p>I learned to clean my raw data and distribute it into “small,” normalized tables. This would eliminate discrepancies, minimize data redundancies, improve data integrity, enhance query performance, simplify data management, and avoid data modification anomalies.</p><p>For instance, I built tables for contacts (joining data from the raw table and my phone book), services provided, spaceship dealers, employees, and spaceships. Things were getting interesting.</p><p>— First I created all the tables. Two examples:</p><pre>CREATE TABLE EmployeesTable (<br>  EmployeeID INT IDENTITY(1, 1) PRIMARY KEY,<br>  Employee NVARCHAR(100),<br>  FirstName NVARCHAR(50),<br>  LastName NVARCHAR(50),<br>  Email NVARCHAR(50),<br>  Phone NVARCHAR(15)<br>  );<br>CREATE TABLE Services_Table (<br>  ServiceID INT IDENTITY(1, 1) PRIMARY KEY,<br>  Timestamp_Created DATETIME,<br>  VehicleID INT,<br>  Stock NVARCHAR(50),<br>  Bill NVARCHAR(50),<br>  Service NVARCHAR(50),<br>  Description NVARCHAR(255),<br>  [$] DECIMAL(10, 2),<br>  EmployeeID INT,<br>  RooftopID INT,<br>  FOREIGN KEY (VehicleID) REFERENCES spaceshipTable(VehicleID),<br>  FOREIGN KEY (EmployeeID) REFERENCES EmployeesTable(EmployeeID),<br>  FOREIGN KEY (RooftopID) REFERENCES SpaceshipDealersTable(RooftopID)<br>  );</pre><blockquote><strong>SQL Personal Toolbox</strong></blockquote><blockquote><em>CREATE TABLE()</em> Creates a table within the data base wit the columns inside the parenthesis. Every column has the name and the type of data.</blockquote><blockquote>DATETIME data type is used to store date and time information together, in the format YYYY-MM-DD HH:MI:SS</blockquote><blockquote>PRIMARY KEY: This constraint ensures that each value in the EmployeeID column is unique and not null, making it the primary key of the table.</blockquote><blockquote>FOREIGN KEY (VehicleID)a constraint that ensures any value entered in the VehicleID column of the Services_Table must already exist in the VehicleID column of the spaceshipTable.</blockquote><blockquote><em>NVARCHAR</em> is a data type in SQL used to store variable-length Unicode character data, with the length in parenthesis (50)</blockquote><p>— And two examples of insert data into tables</p><pre>INSERT INTO EmployeesTable (Employee, FirstName, LastName, Email,Phone)<br>    SELECT rd.Employee,<br>      CASE WHEN CHARINDEX(&#39; &#39;, rd.Employee) &gt; 0 THEN SUBSTRING(<br>      rd.Employee, 1, CHARINDEX(&#39; &#39;, rd.Employee) -1) <br>      ELSE rd.Employee END AS FirstName,<br>      CASE WHEN CHARINDEX(&#39; &#39;, rd.Employee) &gt; 0 THEN SUBSTRING(<br>      rd.Employee,<br>      CHARINDEX(&#39; &#39;, rd.Employee) + 1,<br>      LEN(rd.Employee) - CHARINDEX(&#39; &#39;, rd.Employee)<br>      ) ELSE &#39;&#39; END AS LastName,<br>      cg.E_mail_1_Value,<br>      cg.Phone_1_Value<br>    FROM<br>      raw_data_table rd<br>      LEFT JOIN phone_book_table cg ON rd.Employee = CONCAT(cg.First_Name, &#39; &#39;, cg.Last_Name)<br>      GROUP BY<br>        rd.Employee,<br>        cg.E_mail_1_Value,<br>        cg.Phone_1_Value;<br><br>INSERT INTO Services_Table (Timestamp_Created, VehicleID, Stock, Bill, Service, Description, Price,EmployeeID, RooftopID)<br>SELECT MIN(rd.Timestamp_Created) AS Timestamp_Created<br>    , vt.VehicleID<br>    , rd.Stock<br>    , rd.Bill<br>    , rd.Service<br>    , rd.Description<br>    , rd.Price<br>    , et.EmployeeID<br>    , cd.RooftopID<br>FROM raw_data_table rd<br>INNER JOIN EmployeesTable et ON rd.Employee = et.Employee<br>INNER JOIN SpaceshipDealersTable cd ON cd.Rooftop = rd.Rooftop<br>INNER JOIN spaceshipTable vt ON vt.BAST = rd.BAST<br>GROUP BY vt.VehicleID, rd.Stock, rd.Bill, rd.Service, rd.Description, rd.Price, et.EmployeeID, cd.RooftopID;<br></pre><blockquote><strong>SQL Personal Toolbox</strong></blockquote><blockquote>INSERT INTO populates the given table with the selection from other tables like raw_data_table (rd).</blockquote><blockquote>CHARINDEX(&#39; &#39;, rd.Employee) &gt; 0 Check if there is a space character in the Employee field. And CASE to extract the first name: <strong>If True</strong>:SUBSTRING(rd.Employee, 1, CHARINDEX(&#39; &#39;, rd.Employee) -1): Extracts the substring from the start of Employee up to (but not including) the first space.</blockquote><blockquote><strong>If False</strong>:rd.Employee: Uses the entire Employee field as the first name (if there is no space).</blockquote><blockquote>And a similar query to get the last name <em>SUBSTRING(rd.Employee, 1, CHARINDEX(&#39; &#39;, rd.Employee) +1)</em></blockquote><blockquote>Joins with phone_book_table (cg) to get email and phone information.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ljZKaWlETPnXGwkK7yW8MA.png" /></figure><p>I let myself sink and the journey begins.</p><p>First, I built a custom report to see employee’s performance by-weekly using flexible date ranges depending on when I ran the report.</p><pre>DECLARE @startdate datetime2 = (DATEADD(MONTH, -1, ( DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()), 1)))),<br>@enddate datetime2 = (DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()), 1))<br>-- for last two weeks if it is within the current month<br>DECLARE @startdate datetime2 = DATEFROMPARTS (YEAR(GETDATE()), MONTH(GETDATE()), 1),<br>@enddate datetime2 = DATEFROMPARTS (YEAR(GETDATE()), MONTH(GETDATE()), 16)<br>-- for last two weeks if it is within the previous month<br>DECLARE @startdate datetime2 = DATEADD (MONTH, -1, (DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()), 16))),<br>@enddate datetime2 = DATEADD (DAY, -1, (DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()), 1)))</pre><blockquote><strong>SQL Personal Toolbox</strong></blockquote><blockquote>DECLARE <a href="http://twitter.com/startdate">@startdate</a> datetime2This declares a variable <a href="http://twitter.com/startdate">@startdate</a> of type datetime2</blockquote><blockquote>GETDATE(): Gets the current date and time</blockquote><blockquote>YEAR(GETDATE()) AND MONTH(GETDATE(): Extracts the year and month from the current date.</blockquote><blockquote>DATEFROMPARTS(YEAR(GETDATE()), MONTH(GETDATE()), 1): Creates a date using the extracted year and month, and sets the day to 1.</blockquote><blockquote>DATEADD(MONTH, -1, …): Subtracts one month from the date create, resulting in the first day of the previous month.</blockquote><p>With all these functions pretty much I can set up the query at any date parameter I need. In my case I need first day of last month, last day of last month, first day of current month, 16th date of current month.</p><p>Once I set up the dates to filter the data I build the queries to check billing, starting time, total worked time, and date</p><pre>--Total Billing by Employees<br>SELECT et.Employee<br>  , SUM(st.$) AS [Total Monthly Billin]<br>FROM Employees_Table et<br>INNER JOIN Services_Table st ON et.EmployeeID = st.EmployeeID<br>WHERE Timestamp_Created &gt;= @startdate<br>AND Timestamp_Created &lt; @enddate<br>GROUP BY et.Employee;<br><br>--Day to day by employees<br>SELECT et.Employee<br>    , CONVERT(VARCHAR(5), DATEADD(MINUTE, -30, MIN(CONVERT(TIME, st.Timestamp_Created))), 108) as StartingTime<br>    , DATEDIFF(HOUR, MIN(st.Timestamp_Created), MAX(st.Timestamp_Created)) + 1 as TotalHours<br>    , CAST(st.Timestamp_Created as Date) AS TruncatedDate<br>    , SUM(st.$) as TotalBilledbyDay<br>FROM Employees_Table et<br>INNER JOIN Services_Table st ON et.EmployeeID = st.EmployeeID<br>WHERE Timestamp_Created &gt;= @startdate<br>ANDTimestamp_Created &lt; @enddate<br>GROUP BY Employee,CAST(Timestamp_Created AS DATE)<br>ORDER BY TruncatedDate;</pre><blockquote><strong>SQL Personal Toolbox</strong></blockquote><blockquote>MIN(CONVERT(TIME, st.Timestamp_Created)): Converts the Timestamp_Created to just the time part and finds the minimum time value.</blockquote><blockquote>DATEADD(MINUTE, -30, ...): Subtracts 30 minutes from the minimum time value.</blockquote><blockquote>CONVERT(VARCHAR(5), ..., 108): Converts the resulting time to a string in the format HH:MI (24-hour format)</blockquote><blockquote>DATEDIFF(HOUR, MIN(st.Timestamp_Created), MAX(st.Timestamp_Created)) + 1 as TotalHours</blockquote><blockquote>MIN(st.Timestamp_Created): Finds the earliest timestamp.</blockquote><blockquote>MAX(st.Timestamp_Created): Finds the latest timestamp.</blockquote><blockquote>DATEDIFF(HOUR, ..., ...): Calculates the difference in hours between the earliest and latest timestamps.</blockquote><blockquote>CAST(st.Timestamp_Created as Date): Converts the Timestamp_Created to just the date part, removing the time component.</blockquote><blockquote>And by grouping everything by TruncatedDated, all these values will be showed by day</blockquote><p>I referred to this SQL selection as the “day-to-day report.” I could seamlessly export it to Excel and use pivot tables to generate individual tables for each employee, ensuring a clear and organized presentation. I use this day-to-day report as a temp table for further data analysis:</p><p>- Starting time: Top performers typically began their day early, even when not required to.</p><p>- Total hours worked per day: The best employees consistently worked between 7 and 9 hours.</p><p>- Total billed per day: Even on bad days, the best performers maintained a healthy billing amount.</p><p>By analyzing these metrics — along with money per hour and money per day — I gained insights to help adjust workloads. I could redistribute work for employees working over 40 hours per week (if they wanted), assign more spaceship dealers to those desiring more hours, or offer additional training to improve efficiency and increase earnings per hour.</p><p>The primary goal was to ensure employees were happy — keeping them busy and making good money — which would, in turn, improve both employee retention and customer satisfaction.</p><pre>CREATE TABLE #TempEmployeeReport<br>-- I am using &quot;Day to Day by Employees&quot; to build #TempEmployeeReport<br><br>SELECT Employee<br>    , SUM(TotalHours) / 2 AS HoursperWeek<br>    , SUM(TotalBilledbyDay) as TotalBilled<br>    , SUM(TotalBilledbyDay) * 0.X as AproxComision<br>    , (SUM(TotalBilledbyDay) / SUM(TotalHours)) * 0.X as RatioMoneyperHour<br>    , CONVERT(VARCHAR(5), MIN(StartingTime), 108) AS EarliestDay<br>    , CONVERT(VARCHAR(5), MAX(StartingTime), 108) AS LatestDay<br>FROM #TempEmployeeReport<br>GROUP BY  Employee<br>DROP TABLE #TempEmployeeReport;</pre><blockquote><strong>SQL Personal Toolbox</strong></blockquote><blockquote>SUM(TotalHours) / 2 AS HoursperWeek: Sums the TotalHours and divides by 2 to calculate the average hours per week, assuming a two-week period.</blockquote><blockquote>SUM(TotalBilledbyDay) * 0.X as AproxComision: Calculates the approximate commission by multiplying the total billed amount by a commission rate (represented by 0.X)</blockquote><blockquote>(SUM(TotalBilledbyDay) / SUM(TotalHours)) * 0.X as RatioMoneyperHour: Calculates the ratio of money earned per hour by dividing the total billed amount by the total hours and multiplying by a factor (represented by 0.X).</blockquote><blockquote>CONVERT(VARCHAR(5), MIN(StartingTime), 108) AS EarliestDay: Converts the earliest starting time to a string in the format HH:MI (24-hour format).</blockquote><blockquote>CONVERT(VARCHAR(5), MAX(StartingTime), 108) AS LatestDay: Converts the latest starting time to a string in the format HH:MI (24-hour format)</blockquote><blockquote>GROUP BY Employee Groups the results by the Employee column to perform the aggregations for each employee</blockquote><p>I was ready to showcase my work. I could export these reports to Excel (the Empire’s preferred communication method), format them to make the data clear and actionable, and help the Empire become more efficient and expand its reach.</p><p>Future Plans</p><p>There are still many more questions to answer. My next challenge will be shifting focus from employees to spaceships, concentrating on quality control and accuracy. I’ll investigate spaceships with duplicate service entries to determine whether these duplicates are due to multiple legitimate services or billing errors(Spoiler alert: 20% discrepancy). I’ll also explore automating these types of reports.</p><p>After that, I plan to create views to analyze routes, considering factors like flying time and volume, so I can build more efficient routes for my employees.</p><p>Stay tuned.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7b30d58b9b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>