<?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 Krzysztof Nowak on Medium]]></title>
        <description><![CDATA[Stories by Krzysztof Nowak on Medium]]></description>
        <link>https://medium.com/@krzysieknowak_55470?source=rss-433ad52d2e27------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*BTHZN_HLTrKj1rfLU26eNw.jpeg</url>
            <title>Stories by Krzysztof Nowak on Medium</title>
            <link>https://medium.com/@krzysieknowak_55470?source=rss-433ad52d2e27------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 20:39:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@krzysieknowak_55470/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[Non-equi joins]]></title>
            <link>https://medium.com/@krzysieknowak_55470/non-equi-joins-cc36868b74e7?source=rss-433ad52d2e27------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc36868b74e7</guid>
            <category><![CDATA[r]]></category>
            <category><![CDATA[rstats]]></category>
            <category><![CDATA[challenge]]></category>
            <dc:creator><![CDATA[Krzysztof Nowak]]></dc:creator>
            <pubDate>Tue, 10 Sep 2024 09:07:11 GMT</pubDate>
            <atom:updated>2024-09-10T10:20:21.290Z</atom:updated>
            <content:encoded><![CDATA[<p>In this short article I will show example of using Non-equi in R, with special emphasis on <em>between</em> operator, which makes syntax closer to natural language.</p><p>We will try to use it for one of <a href="https://www.linkedin.com/posts/excelbi_excel-challenge-problem-activity-7238758032132714496-0XXU?utm_source=share&amp;utm_medium=member_desktop">EXCEL BI Challenges</a> published on LinkedIn. These challenge consists of more steps, so before we dive into it, let’s practice on very simple example.</p><h4><strong>Simple example</strong></h4><p>Imagine that you would like to assign a Job Band to position based on salary ranges. You have a list of salaries:</p><pre># Create a vector of salaries<br>salaries &lt;- c(1050, 2200, 4777)<br><br># Create a data frame<br>salaries_df &lt;- data.frame(Salary = salaries) </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gW7SpEih674qbHmOJmULfQ.png" /></figure><p>And salary ranges with a job bands:</p><pre># Create vectors for job bands and their salary ranges<br>job_bands &lt;- c(1, 2, 3)<br>bottom_range &lt;- c(0, 501, 2500)<br>upper_range &lt;- c(500, 2501, 15000)<br><br># Create a data frame<br>job_bands_df &lt;- data.frame(Job_Band = job_bands, <br>                            Bottom_Range = bottom_range, <br>                            Upper_Range = upper_range)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I18oGp2-RYVNATg6IYjSQQ.png" /><figcaption>Ranges</figcaption></figure><p>Your task is to bring Job Band column into Salaries table. The Job Ranges table presents 2 problems for classic join technique:</p><ol><li>We have more than one column to be use as reference</li><li>A quick look at data shows that none of actual salaries match the values in range columns.</li></ol><p>Our goal is to find the job band for which salary falls between Bottom and Upper range. Let’s take salary 2200. It is between 501 and 2500. Job band 2 seems correct.</p><p>How to solve this problem?</p><pre>library(tidyverse)<br><br>salaries_df |&gt; # Main table<br>  left_join(job_bands_df, # Table from which we extract data<br>            join_by(between(Salary, <br># Column to be compared to bottom and upper range<br>                            Bottom_Range,#Lower boundary<br>                            Upper_Range))) #Upper boundary </pre><p>Our code snippet requires the <strong>tidyverse</strong> library.</p><p>In the first step we define our main table: the one with actual salaries. Next, in left join clause we define table with data to be extracted (job bands).</p><p>Then crucial part happens. <strong>Between</strong> operator asks us to define following equation: Salary &gt;= Bottom_Range and Salary &lt;= Upper_Range). It basically means: Salary <em>is between</em> lower and upper range.</p><p><strong>Result</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RZ-JtVtN9GRsl2i455auhA.png" /><figcaption>All columns combined</figcaption></figure><h4><strong>Excel BI Challange</strong></h4><p>Lets check more complex problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lTkxHrPCp9DLa6uQgYCRCQ.png" /><figcaption>EXCEL CHALLENGE 539</figcaption></figure><p>First thing i want to achieve is to structure Table 1 so it reminds our example.</p><pre>T1 |&gt;<br>  pivot_longer(cols = 3:ncol(T1), names_to = &quot;Ranges&quot;, values_to = &quot;Prices&quot;) |&gt;<br>  separate(col = Ranges, into = c(&quot;Low&quot;, &quot;Max&quot;), sep = &quot;-&quot;) |&gt;<br>  mutate(<br>    Low = as.numeric(str_extract(Low, &quot;\\d+&quot;)),<br>    Max = if_else(is.na(Max), Inf, as.numeric(Max))<br>  )</pre><p>Now all ranges are visible in Low and Max columns and every row represents its connection with Item.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f9z3Jejk1XbxDhAcD6UofA.png" /><figcaption>Table 1 transformed</figcaption></figure><p>Now our join comes to action:</p><pre>T2 |&gt;<br>  left_join(LM, join_by(Item == Item, between(Quantity, Low, Max))) |&gt;<br>  select(Item, Quantity, Prices) </pre><p>In this case, before we use <em>between</em>, we ensure that also Item is mentioned as table Key. As you can see, every combination of item and quantity receives its price.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oWf-TU4SBnhTVaI4EszrrA.png" /><figcaption>Join results</figcaption></figure><p>Remaining part is to calculate mean and choose a way how numbers are displayed</p><pre>#Full solution<br>Answer &lt;- T2 |&gt;<br>  left_join(LM, join_by(Item == Item, between(Quantity, Low, Max))) |&gt;<br>  select(Item, Quantity, Prices) |&gt;<br>  summarise(Average = mean(Prices), .by = c(Item, Quantity)) |&gt;<br>  mutate(Answer = scales::comma(Average * Quantity, big.mark = &quot;&quot;, decimal.mark = &quot;,&quot;)) |&gt;<br>  select(-c(Average))<br><br>print(Answer)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*TvgpiUBoq2hdWVDdV0lDig.png" /><figcaption>Full solution</figcaption></figure><p>Whole code is available on my <a href="https://github.com/KrzysztofNowakJaw/Excel_BI_Challanges/blob/c12b69d68f052e9e8a047b0eb0a7c3e5bcc24995/Excel_Challenge_539%20-%20Total%20Amount%20Per%20Item.R">GitHub</a> (press)</p><p>Thanks you reading.</p><p>Please don’t forget to check other <a href="https://www.linkedin.com/in/excelbi/">Excel BI challages</a></p><p>#R #Rstats #datawrangling #challange</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc36868b74e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fix dates with regular expressions and R]]></title>
            <link>https://medium.com/@krzysieknowak_55470/fix-dates-with-regular-expressions-and-r-9cdc49376de2?source=rss-433ad52d2e27------2</link>
            <guid isPermaLink="false">https://medium.com/p/9cdc49376de2</guid>
            <category><![CDATA[time-intelligence]]></category>
            <category><![CDATA[r]]></category>
            <category><![CDATA[regular-expressions]]></category>
            <category><![CDATA[rstudio]]></category>
            <category><![CDATA[data-wrangling]]></category>
            <dc:creator><![CDATA[Krzysztof Nowak]]></dc:creator>
            <pubDate>Sat, 01 Jul 2023 15:02:00 GMT</pubDate>
            <atom:updated>2023-07-01T15:02:00.133Z</atom:updated>
            <content:encoded><![CDATA[<p>In this short post, I will show one way to standardize dates. Our tools will be the R language and its text functions along with regular expressions.</p><p>To the point.</p><p>Imagine that you get a report in which the date column contains values with different order of components .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/230/1*Q2a1ViIbTXMx4zbv0uqXWg.png" /><figcaption>Original date columns</figcaption></figure><p>As we can see, there is quite a mess here. The date components are not only arranged in different order, we also have different separators.</p><p>We would like our dates to be presented in Year-Month-Day format</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/174/1*TDj8RE0aulbY9Ws-2Pl_SQ.png" /><figcaption>Expected result</figcaption></figure><p>To achieve this goal, we will start with a few assumptions. We see that in our input table the year is always represented by 4 digits, the month by 2 digits and the month its full name.</p><p>We will now use the <strong>str_view</strong> function to identify these components using regular expressions. Lets start with 4 digit year.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*oM6DdcsH0rQLDAcqo1w68A.png" /><figcaption>Regex and visual representation</figcaption></figure><p>Our function takes 2 arguments. <br>1.Source. First the name of the table and after the $ sign the name of the column<br>2.Pattern. We use the tag “\\b”, which marks the beginning of the word. Then we point to the digits (“\\d”) and indicate that they should occur exactly 4 times (“{4}”). Then we state that this is the word boundary — again “\\b”.</p><p>For the day, the solution is almost identical, we only change the number of digits to 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*zqPBmfzbwc4GHzQ2HrtSsA.png" /><figcaption>Regex for month</figcaption></figure><p>For the name of the month, we will use the expression “[[:alpha:]]+”, which means that we are looking for letters (“[[:alpha:]]”) and that they occur once or more (“+”).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*XcxBIOwL_nOStEPsDQVV_A.png" /><figcaption>Regex for month</figcaption></figure><p>Next we will replace the str_view function, which does not create new objects, with the str_glue function, which deals with combining selected components. It will include the str_extract function, which extracts specific components from the selected text.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*GGA5eM5nOYCHKpy7BZaY5w.png" /><figcaption>Change order of date components</figcaption></figure><p>Let’s take a look at how this function works.In the second section the function creates 3 objects:year,month,day. Using the str_extract function and our expressions, we identify the individual components of the date. With these at our disposal, we create the expression “{Year}-{Month}-{Day}”. We specify the order and separator in it.</p><p>To make our solution more versatile and modular, we will encapsulate the whole thing in a function that additionally converts the finished text to a column in Date format.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*lh3ZIG2XgcK9GkMheTYOHQ.png" /><figcaption>Reusable function</figcaption></figure><p>We used the mutate function using overwrite the Date column with the result of applying our custom function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*mBN9apredL0I4GifmVKXbg.png" /><figcaption>Application of fuction</figcaption></figure><p>All the functions used are available through the tidyverse library.</p><p>Thank You for reading</p><p>#regex #R #Rstats #datawrangling</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9cdc49376de2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamic pivot tables in SQL]]></title>
            <link>https://medium.com/@krzysieknowak_55470/dynamic-pivot-tables-in-sql-434de3002c91?source=rss-433ad52d2e27------2</link>
            <guid isPermaLink="false">https://medium.com/p/434de3002c91</guid>
            <dc:creator><![CDATA[Krzysztof Nowak]]></dc:creator>
            <pubDate>Mon, 13 Jun 2022 18:24:11 GMT</pubDate>
            <atom:updated>2022-06-13T18:24:11.240Z</atom:updated>
            <content:encoded><![CDATA[<p>A few months ago I published a short note on how to create a pivot table in SQL. Today I would like to show you a more scalable solution.</p><p>Let’s take a look at the following table</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*1FxFOJQ_KH6a4fAqlLA4SA.png" /><figcaption>Data set</figcaption></figure><p>Imagine you want a pivot table that summarizes the monetary values (Amount) so that the regions are in rows and the years are in columns.</p><p>When creating a pivot table in SQL we need to define the level of dispersion (columns).These are specific values, for example, specific years.<br>If you know that your company operated in different regions from 2020 to 2022 (inclusive) then the profit in the last two years must be marked as :<br>SUM(Money_value) FOR Year IN([2021], [2022]).</p><p>Not particularly dynamic, is it? After one year, it’s no longer the last 2 years.</p><p>Below, the highlighted section shows that we had to enter specific years as columns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*qHPKLzH80fjSNkP6r6qOSQ.png" /><figcaption>Static solution with selected years</figcaption></figure><p>One solution is to use DENSE_RANK() function, which will assign each year ranking in descending order. This allows us to turn specific years into rank positions. This solution should dynamically assign the position of the last and second to last year</p><p>Lets see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*exrATqddLg8zWmNckEDLzg.png" /><figcaption>Solution with rank position</figcaption></figure><p>We can go deeper to see how rank has been applied:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*M81MgJ9NZlMjrNDagUkMqA.png" /><figcaption>Dense rank</figcaption></figure><p>The DENSE_RANK() function first sorts the years in descending order and then assigns a ranking position to each unique year. As shown by the MAX() function, 2022 is the last year and it receives a ranking position of 1</p><p>Finally, how to pivot columns? Lets look at last section of code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*mleDdMDqNqcyxtlpCeAv-Q.png" /><figcaption>Pivoting</figcaption></figure><p>We need all columns from previous CTE (i have a note about CTE).</p><p>PIVOT function arguments are:</p><p>SUM: we sum up money values but you cant use also COUNT or AVG, depends on data and purpose.</p><p>FOR Year_Rank IN: selection of columns. We choose years position.</p><p>Thats all.</p><p>Enjoy!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=434de3002c91" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQL Top function and RANKX function for DAX Studio]]></title>
            <link>https://medium.com/@krzysieknowak_55470/sql-top-function-and-ranx-function-for-dax-studio-6a50e42079b5?source=rss-433ad52d2e27------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a50e42079b5</guid>
            <category><![CDATA[dax-studio]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[power-bi]]></category>
            <category><![CDATA[dax]]></category>
            <dc:creator><![CDATA[Krzysztof Nowak]]></dc:creator>
            <pubDate>Mon, 25 Oct 2021 22:08:44 GMT</pubDate>
            <atom:updated>2021-11-15T23:39:35.801Z</atom:updated>
            <content:encoded><![CDATA[<p>Hey,</p><p>After holiday Im coming back with simple exercise. Purpose is to count orders on 2 aggregation levels — country and city and to assign ranking position and limit results to best 5.</p><p>We will use popular Superstore dataset.</p><p>We are about to count sales and aggregate results over country and city level.</p><p>SQL query looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6WfBgGcxy-QbDzb03z_XNA.png" /><figcaption>SQL Query</figcaption></figure><p>Our steps:</p><p>1. Create CTE in which we set aggragation levels: country and city</p><p>2. We count rows over country and city partitions and call result as NoOfTrades</p><p>3. We extract results. First we choose to display all (*) results.</p><p>4. We choose top 5 results</p><p>5. We label results with ranking position over NoOfTrades value</p><p>Below, DAX Studio version:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*eWlm7IFBcp8faLIXvnP6Sg.png" /><figcaption>DAX Studio</figcaption></figure><p>1. First we define measure in which we count rows in orders table</p><p>2. In summarize function we define grouping columns</p><p>3. We add results of 1 step calculation undef “Qty” alias</p><p>4. Additional column is ranking function which assings position by result value from step 3</p><p>5. All is embedded in FILTER function which limits ranking results to 1 to 5.</p><p>Hope you like it ;)</p><p>Regards</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a50e42079b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multiple SQL queries filtered with predefined variable]]></title>
            <link>https://medium.com/@krzysieknowak_55470/multiple-sql-queries-filtered-with-predefined-variable-fe5bebdcddad?source=rss-433ad52d2e27------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe5bebdcddad</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[business-intelligence]]></category>
            <category><![CDATA[variables]]></category>
            <dc:creator><![CDATA[Krzysztof Nowak]]></dc:creator>
            <pubDate>Sun, 05 Sep 2021 21:01:44 GMT</pubDate>
            <atom:updated>2021-09-13T22:11:45.788Z</atom:updated>
            <content:encoded><![CDATA[<p>Lets imagine that you are going to created 3 separated reports:</p><ol><li>Shows products for which price is higher or equal than average -<strong>333</strong>.</li><li>Shows transactions related only to products for which price is higher or equal that average</li><li>Shows regions where products which price higher or equal average were sold</li></ol><p>Common thing is filter exluding products with price below average.</p><p>Results should look like below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/188/1*qqiJwnxu8_Rxb9HWJphSxw.png" /><figcaption>First query result. Only one price above average</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/89/1*9vqDDDnuMzg_BNnFTOo8MA.png" /><figcaption>Second query result</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/86/1*SBfM7sV_eekb_tR6yyFhNQ.png" /><figcaption>Third query result</figcaption></figure><p>Question is — can we avoide calculating average price in every query?</p><p>Yes, lets try to define viariable which name can be used accross every query:</p><p>First step is to declare variable name (after “@”) and type. In our case it will be integer, but can be also MONEY or FLOAT, its up to you. Please note that one “@” sign means local variable, “@@” means global variable — but its more complex stuff.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*C2OraxTdtgbTNHhy9VpP4Q.png" /><figcaption>Variable definition</figcaption></figure><p>After that we set a query witch results with single value representing average price. Lets start with SET clause. Query is preaty simple, uses AVG funcion on one table. Average is 333. You can check it with “ PRINT @Average_price” command.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/186/1*7bTVL9r6xCZyYUqTenacgg.png" /><figcaption>Products table</figcaption></figure><p>Now, when you looks for prices higher that average you use “@Average_price” as criteria.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*pIhBh3mFPcQlwVfNNrbOYQ.png" /><figcaption>Firts query. WHERE clause contains our variable</figcaption></figure><p>Likewise, we will use this variable in second and third query.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*5iFWbcUwj25aV_UVAxB-qw.png" /><figcaption>Second query</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*1NxxhMMJ1FuClyO4K0s79w.png" /><figcaption>Third query</figcaption></figure><p>As you can see we defined average only ones, which has many advantages. For example if you want check not average but e.i MAX / MIN Price you amend it only in variable definition and it affects all queries.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe5bebdcddad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pivot Table in SQL for Sales Analise ? Sure!]]></title>
            <link>https://medium.com/@krzysieknowak_55470/pivot-table-in-sql-for-sales-analise-sure-32892941f872?source=rss-433ad52d2e27------2</link>
            <guid isPermaLink="false">https://medium.com/p/32892941f872</guid>
            <category><![CDATA[business-intelligence]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[sql-pivot]]></category>
            <dc:creator><![CDATA[Krzysztof Nowak]]></dc:creator>
            <pubDate>Thu, 02 Sep 2021 18:47:41 GMT</pubDate>
            <atom:updated>2021-09-06T20:23:14.889Z</atom:updated>
            <content:encoded><![CDATA[<h3>Pivot Table in SQL for Sales Analise ?</h3><p>Lets consider three tables:</p><ol><li>Dimension table with Products ID’s and Names:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/221/1*HfRG3oYjNnpCSdthfpjbOw.png" /><figcaption>Our_Products Table</figcaption></figure><p>2. Sales History table with ProductID,SalesId and RegionID</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*WH_GBdN8qUG4gYfKBNfzag.png" /><figcaption>Sales_Info Table</figcaption></figure><p>3.Regions Table</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*T8tMfhwUuxqpFfGqSj6S4g.png" /><figcaption>Regions table</figcaption></figure><p>All of them can be connected</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*qACojma21s_NuDWVbwc3VQ.png" /><figcaption>Products to Sales</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*R8MMvTPfeaTNf5O9WCH20w.png" /><figcaption>Sales to Regions</figcaption></figure><p>Final results should presents number of sales orders for every product in every Region and mark product/products never sold.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*0LHaj_pTcNn1kEJtSRb-lA.png" /></figure><p>How do we start? We will write two common table expressions. First with narrow products table to those product ids which can be found in sales table. We use EXIST operator to perform logical test — result will show only those products that occures in Sales table (In the end of article i add link do EXIST explanation).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*Q6weFFWUhbWyd0AJAuu0ng.png" /><figcaption>Products visible in Sales Table</figcaption></figure><p>In this subquery we add column which is just a string and label product as sold.</p><p>Now, we create asymmetric CTE which looks for trades never sold. NOT EXIST operator is used. (In my first article i explain how to start first and following CTE)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*O6WMqLJTF7axQ7W9y_soxw.png" /><figcaption>Products NOT visible in Sales Table</figcaption></figure><p>Now, lets combine those queries. “Sold” and “Never sold” are crucial to distinguish those two subsets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/153/1*nVod7XZ0yHOAr5f8uo_8xw.png" /><figcaption>Queries appended</figcaption></figure><p>You must note that those 2 queries needs to have same structure — in this case 3 columns of same type.</p><p>Results is like below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/1*M0hB-tWujWwhQ9PCud-C7w.png" /><figcaption>Sold + no sold products</figcaption></figure><p>Now, lets prepare to Pivot table. Lets define our final subquery where we join previous results with sales and regions table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*be7Kk5wJnb9nUQ-OUO3vaw.png" /><figcaption>Sold/never sold products joined with sales and regions table</figcaption></figure><p>Here, we finish our task:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*AsUnqo-XPW-zoA1PAnbszQ.png" /><figcaption>Pivot table query</figcaption></figure><p>How does it work?</p><ol><li>You choose all (*) columns from above query</li><li>You determine aggregation — in our case we count sales order per product</li><li>You determine dispersion level (columns) — in our case regions.</li></ol><p>Here we are!</p><p><a href="https://docs.microsoft.com/en-us/sql/t-sql/language-elements/exists-transact-sql?view=sql-server-ver15">https://docs.microsoft.com/en-us/sql/t-sql/language-elements/exists-transact-sql?view=sql-server-ver15</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32892941f872" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Is bestseller most profitable? Lets check with SQL]]></title>
            <link>https://medium.com/@krzysieknowak_55470/is-best-seller-most-profitable-lets-check-with-sql-97f70030b3e9?source=rss-433ad52d2e27------2</link>
            <guid isPermaLink="false">https://medium.com/p/97f70030b3e9</guid>
            <category><![CDATA[business-intelligence]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[window-functions]]></category>
            <dc:creator><![CDATA[Krzysztof Nowak]]></dc:creator>
            <pubDate>Sun, 29 Aug 2021 16:53:21 GMT</pubDate>
            <atom:updated>2021-08-29T16:54:13.290Z</atom:updated>
            <content:encoded><![CDATA[<p>Lets take following table. It shows product name, sales number, price and area of sales.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/369/1*YeHzBigDp0MUKgLoZk4UGg.png" /><figcaption>Source table</figcaption></figure><p>We would like to know:</p><ol><li>What is quantity of sales orders Per Product</li><li>What is absolute quantity of sales orders</li><li>What is percentage share of value from point 1 in value from point 2.</li><li>Same comparision for money value</li><li>We would like to assing ranking value to every product basing of above shares.</li><li>Check if bestseller per quantity of sales orders is also most profitable in money terms.</li></ol><p>We gonna use :</p><ol><li>Subquery</li><li>Window functions which will change context filter from Product-granuality to scalar values.</li><li>CASE clause to perform conditional formating</li><li>CAST function to convert format</li></ol><p>Lets start from internal query:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zi5cZc3cUseoa4xbGm7zuw.png" /><figcaption>Internal query</figcaption></figure><p>After standard Count/ Sum phrase we see OVER () clause in which we define partition (Aggregation level). In first case, it will be Product Name. If we dont define partition, function will not split results into categories.</p><p>To count Pct Share, we divide results per Product by scalar value. Internal cast function will convert results to decimal. External to string so we can add “%” sign.</p><p>Results is below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*nyWXnQIqcKExKxH9pu7eiQ.png" /><figcaption>Result of internal query</figcaption></figure><p>However, we dont need full info in final view.</p><p>We close what we done in subquery “InitialCal”.</p><p>Lets see external query which produce final result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hAPHgEK67DP_rIA4ymmVEw.png" /><figcaption>External query</figcaption></figure><p>After choosing Product name we use ROW_NUMBER () OVER () function which assigns ranking position by ShareofSoldItemsQuantity value from subquery in descending order.</p><p>Same for ShareofSoldItemsCash</p><p>Lets look at CASE Function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*HPPHHmkN1I8x-d9MathjGA.png" /><figcaption>Case function</figcaption></figure><p>In case when Ranking Position is the same for quantity and money, we can say that product is Best per Quantity and Cash.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97f70030b3e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Utilizing Window Function for Ranking comparison in SQL]]></title>
            <link>https://medium.com/@krzysieknowak_55470/utilizing-window-function-for-ranking-comparison-in-sql-4cb5f2f787ad?source=rss-433ad52d2e27------2</link>
            <guid isPermaLink="false">https://medium.com/p/4cb5f2f787ad</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[window-functions]]></category>
            <category><![CDATA[business-intelligence]]></category>
            <dc:creator><![CDATA[Krzysztof Nowak]]></dc:creator>
            <pubDate>Fri, 27 Aug 2021 12:47:12 GMT</pubDate>
            <atom:updated>2021-08-29T15:00:53.071Z</atom:updated>
            <content:encoded><![CDATA[<p>Lets imagin that we have Sales table that presents 3 products, order numbers and regions where they were sold.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/1*Nd--Qo9xcqEmxWgRRDqFjQ.png" /><figcaption>Sales table</figcaption></figure><p>Our goal is to check what is ranking position for every product per Region and quantity of sales orders.</p><p>Our results should looks like that. For example we know that Helmets were bestsellers in Nevada, but in Texas Bikes did better job.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/297/1*avKQf-B5sLM8ALaBG7n0XQ.jpeg" /></figure><p>How do we achieve that?</p><p>My idea is to create separated Common table expression for every region, count salesorders and rank products per sales quantity.</p><p>Lets see example CTE:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*tWdfb8c-3EFBqy2AcOq1bg.png" /><figcaption>Sample CTE for Texas</figcaption></figure><p>What is happening here? First we create a table with AnaliseForTexas name.</p><p>We choose ProductName as agregation level — sales will be counted per Name.</p><p>Now, we go to window function. DENSE_RANK () is function which assign ranking position for every Product and its argument is COUNT(SalesOrderID) — function which counts sales and order results in descending order.</p><p>In next step we filter out region with WHERE and GROUP BY results by ProductName column — as said before, it is our aggregation level.</p><p>We need to repeat this operations for every region, however we need to use “WITH” word only ones. Second CTE starts with Alias:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/1*p9qLcNDPk8YQNPXbq3ZXfg.png" /><figcaption>nCTO without WITH</figcaption></figure><p>So, we have 4 CTE and we would like to join them to presents every ranking position. Primary Key for every join is ProductName. We also extract Ranking colums for every region.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*pu-KLD3qbVPBUT-pfYgPOw.png" /></figure><p>Hope you will enjoy using windows function.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4cb5f2f787ad" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>