<?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 Vivian on Medium]]></title>
        <description><![CDATA[Stories by Vivian on Medium]]></description>
        <link>https://medium.com/@vyvring?source=rss-ab6b8437d0a2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ts8sVPtSMkPU8r5MRaUYag.png</url>
            <title>Stories by Vivian on Medium</title>
            <link>https://medium.com/@vyvring?source=rss-ab6b8437d0a2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 16:26:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vyvring/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[Multiple values matching multiple columns(many-to-many match) (Snowflake)]]></title>
            <link>https://medium.com/@vyvring/multiple-values-matching-multiple-columns-many-to-many-match-snowflake-b27550d4af1?source=rss-ab6b8437d0a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/b27550d4af1</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Vivian]]></dc:creator>
            <pubDate>Fri, 02 Jun 2023 07:57:26 GMT</pubDate>
            <atom:updated>2023-06-02T07:57:26.740Z</atom:updated>
            <content:encoded><![CDATA[<p>While loading raw data into database, it is possible that one raw data is split to multiple tables so that each subset table might require different actions. Assuming actions can be ‘Insert’, ‘Update’ or ‘Delete’.</p><h3>Sample data</h3><p>To simplify the raw data, only row id is kept in the sample data. The raw data will be split to 3 tables thus three action columns are calculated.</p><pre>create or replace temp table table1<br>(<br> row_id int,<br> action1 char(1),<br> action2 char(1),<br> action3 char(1)<br>);<br><br>insert into table1<br>values (1,&#39;I&#39;,&#39;U&#39;,null),<br>(2,null,&#39;I&#39;,null),<br>(3,null,null,&#39;D&#39;),<br>(4,&#39;U&#39;,null,&#39;I&#39;),<br>(5,null,null,null);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*a9I4do4AmkJHkOqftml96Q.png" /><figcaption>Raw data with actions</figcaption></figure><p>The rows with either ‘insert’ or ‘update’ actions are selected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*9N1owKpy2soBBaOqPLwDDA.png" /><figcaption>Expected output</figcaption></figure><h3>Solution</h3><h4>Method 1</h4><p>Each action column is checked if the value is ‘I’ or ‘U’.</p><pre>select * from table1 <br>where action1 in (&#39;U&#39;,&#39;I&#39;) or action2 in (&#39;U&#39;,&#39;I&#39;) or action3 in (&#39;U&#39;,&#39;I&#39;)</pre><h4>Method 2</h4><p>The fixed values can be swapped to the left of the <em>‘in’</em> operator.</p><pre>select * from table1 <br>where &#39;U&#39; in (action1,action2,action3) or &#39;I&#39; in (action1,action2,action3)</pre><h4>Method 3</h4><p>Two arrays can be formed to compare with each other. The function <em>array_construct()</em> converts three actions to an array. The overlap with another array formed by two fixed values is checked by the function <em>array_overlap().</em></p><pre>select * from table1 <br>where arrays_overlap([&#39;U&#39;,&#39;I&#39;], array_construct(action1,action2,action3));</pre><h4>Method 4</h4><p>Two fixed values can form a lookup table using the function <em>split_to_table()</em>.</p><pre>select * from table(split_to_table(&#39;U,I&#39;,&#39;,&#39;));</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/1*CP89jkFAfqe1W1ehjWFbIA.png" /><figcaption>Output of split_to_table()</figcaption></figure><pre>select * from table1 t1<br>where exists <br>(<br>  select 1 <br>  from table(split_to_table(&#39;U,I&#39;,&#39;,&#39;)) t2<br>  where t2.value in (action1,action2,action3)<br>);</pre><h4>Method 5</h4><p>The pattern search in regular expression functions can scan multiple matching values. The function <em>array_to_string()</em> converts an array to a string. The function <em>regex_instr()</em> searches multiple matching patterns by separating them by ‘|’.</p><pre>select * from table1<br>where regexp_instr(<br>  array_to_string(array_construct(action1,action2,action3),&#39;&#39;)<br>  ,&#39;U|I&#39;,1,1,0,&#39;i&#39;)&gt;0;</pre><h4>Method 6</h4><p>We can also use exclusion logic by excluding rows without any action and rows only have ‘delete’ actions. The function <em>array_construct_compact()</em> removes null (undefined) values and the function <em>array_distinct()</em> removes duplicate elements in an array.</p><pre>select * from table1<br>where array_distinct(<br>  array_construct_compact(action1,action2,action3)<br>) not in ([],[&#39;D&#39;]);</pre><h4>Method 7</h4><p>The function <em>nullif()</em> returns null if the action is ‘D’, otherwise returns the action column value. The rows will be kept if all action columns are neither null nor ‘D’.</p><pre>select * from table1<br>where not(<br>  nullif(action1,&#39;D&#39;) is null and <br>  nullif(action2,&#39;D&#39;) is null and <br>  nullif(action3,&#39;D&#39;) is null<br>);</pre><p>In conclusion, the method 1 and 2 are common methods that are quite straight forward and easy to read. The method 3, 4 and 5 are more flexible in a SQL function or procedure, where the lookup values can be replaced as a parameter to allow passing through dynamic lookup inputs. The method 6 and 7 could save the code maintenance work if the exclusion list is always unchanged while the inclusion criteria are extended.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b27550d4af1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Matching multiple columns (one-to-many match)(Snowflake)]]></title>
            <link>https://medium.com/@vyvring/matching-multiple-columns-one-to-many-match-snowflake-5a5675796e30?source=rss-ab6b8437d0a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a5675796e30</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Vivian]]></dc:creator>
            <pubDate>Fri, 26 May 2023 08:01:47 GMT</pubDate>
            <atom:updated>2023-05-26T08:01:47.774Z</atom:updated>
            <content:encoded><![CDATA[<h3>Matching multiple columns (one-to-many match) (Snowflake)</h3><p>The wide-form (flat) data is widely used in business to store all the related information in one row per loan application. It is common that one loan application with multiple applicants requires to retrieve extra information from other long-form data.</p><h3>Sample data</h3><p>We have a simplified application data with multiple columns recording customer ids.</p><pre>create or replace temp table table1<br>(<br> id int,<br> app_date date,<br> customer1 varchar(10),<br> customer2 varchar(10),<br> customer3 varchar(10)<br>);<br><br>insert into table1<br>values (1,&#39;2023-02-02&#39;,&#39;CP39021&#39;,&#39;CP29864&#39;,null),<br>(2,&#39;2023-02-16&#39;,&#39;CP23974&#39;,&#39;CP39021&#39;,null),<br>(3,&#39;2023-03-07&#39;,&#39;CP29864&#39;,&#39;CP10237&#39;,&#39;CP29374&#39;),<br>(4,&#39;2023-03-11&#39;,&#39;CP23904&#39;,null,null);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*ymuUqBeBoQreBOLSteT-Fw.png" /><figcaption>Application Table</figcaption></figure><p>The customer table records personal details of individuals.</p><pre>create or replace temp table table2<br>(<br> customer_id varchar(10),<br> first_name varchar(20),<br> last_name varchar(20)<br>);<br><br>insert into table2<br>values (&#39;39021&#39;,&#39;Peter&#39;,&#39;Jones&#39;),<br>(&#39;29864&#39;,&#39;Jane&#39;,&#39;Jones&#39;),<br>(&#39;23904&#39;,&#39;Ted&#39;,&#39;Brown&#39;),<br>(&#39;29374&#39;,&#39;Rob&#39;,&#39;Evans&#39;),<br>(&#39;10237&#39;,&#39;Kat&#39;,&#39;Davies&#39;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/1*QEi8Bg2GS-UJihetWTlemQ.png" /><figcaption>Customer Table</figcaption></figure><p>The business request is to report number of application by individual customers, which requires to merge two tables. The expected output data is as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*UEYL9VD1tnuLawgXIo-NhQ.png" /><figcaption>Expected output data</figcaption></figure><h3>Solution</h3><p>It is a <strong>one-to-many</strong> join that one application could match multiple customers.</p><h4>Method 1</h4><p>The ‘<em>or</em>’ operator can be used to match multiple columns.</p><pre>select <br> t1.id,<br> t1.app_date,<br> t2.first_name||&#39; &#39;||t2.last_name as customer_name<br>from table1 t1,table2 t2<br>where t2.customer_id = t1.customer1 <br>or t2.customer_id = t1.customer2 <br>or t2.customer_id = t1.customer3;</pre><h4>Method 2</h4><p>The ‘<em>in</em>’ operator can achieve the same outcome since only one column in table2 is used to compare with 3 columns in table1. The code can be rewritten as below.</p><pre>select <br> t1.id,<br> t1.app_date,<br> t2.first_name||&#39; &#39;||t2.last_name as customer_name<br>from table1 t1,table2 t2<br>where t2.customer_id in (t1.customer1,t1.customer2,t1.customer3);</pre><h4>Method 3</h4><p>The comparison can be more general using the ‘<em>like any</em>’ operator if it is a partial string or pattern matching situation .</p><pre>select <br> t1.id,<br> t1.app_date,<br> t2.first_name||&#39; &#39;||t2.last_name as customer_name<br>from table1 t1,table2 t2<br>where t2.customer_id like any (t1.customer1,t1.customer2,t1.customer3);</pre><h4>Method 4</h4><p>Snowflake is also allowed searching for an element in a SQL array by the function ‘<em>array_contains()’</em>. The 3 customer ids can form an array using the function ‘<em>array_construct()’</em>.</p><pre>select <br> t1.id,<br> t1.app_date,<br> t2.customer_id,<br> t2.first_name||&#39; &#39;||t2.last_name as customer_name<br>from table1 t1,table2 t2<br>where array_contains(t2.customer_id::variant,<br>array_construct(t1.customer1,t1.customer2,t1.customer3));</pre><h4>Method 5</h4><p>Referring to the <a href="https://medium.com/@vyvring/joining-two-fields-that-require-string-transformation-snowflake-beedc2855544">partial string matching</a> discussion in my previous article, the concatenated data can be created using the function <em>‘concat_ws</em>’, which allows searching the customer id of table2 in 3 columns of table1 at once. However, the null values in columns need to be taken care of by the function ‘<em>ifnull()’</em>.</p><pre>select <br> t1.id,<br> t1.app_date,<br> t2.first_name||&#39; &#39;||t2.last_name as customer_name<br>from table1 t1,table2 t2<br>where concat_ws(&#39;|&#39;,ifnull(t1.customer1,&#39;&#39;),ifnull(t1.customer2,&#39;&#39;),ifnull(t1.customer3,&#39;&#39;)) <br>like &#39;%&#39;||t2.customer_id||&#39;%&#39;;</pre><p>In conclusion, The ‘<em>in</em>’ operator is more efficient than the ‘<em>or</em>’ operator for full string multi-value matching. The rest of methods are more flexible if there is a sub-string, pattern or more complex matching.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a5675796e30" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting the row containing the maximum value (Snowflake)]]></title>
            <link>https://medium.com/@vyvring/getting-the-row-containing-the-maximum-value-snowflake-6920d9388a54?source=rss-ab6b8437d0a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/6920d9388a54</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[snowflake]]></category>
            <dc:creator><![CDATA[Vivian]]></dc:creator>
            <pubDate>Fri, 19 May 2023 07:57:47 GMT</pubDate>
            <atom:updated>2023-05-19T07:57:47.310Z</atom:updated>
            <content:encoded><![CDATA[<p>Sometimes the entire data row containing the maximum value needs to be retrieved from the data for further data merging or calculation.</p><h3>Sample data</h3><p>Assuming the example data has two items and their sales balance from Feb-Apr23.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*vQ--nw0IbGVGBDQ_ulW3UQ.png" /><figcaption>Sale amount per month</figcaption></figure><pre>create or replace temp table table1<br>(<br> id int,<br> date_of_month date,<br> sale_balance int<br>);<br><br>insert into table1<br>values (1,&#39;2023-02-01&#39;,1000),<br>(1,&#39;2023-03-01&#39;,2000),<br>(1,&#39;2023-04-01&#39;,1050),<br>(2,&#39;2023-02-01&#39;,1000),<br>(2,&#39;2023-03-01&#39;,1100),<br>(2,&#39;2023-04-01&#39;,1300);</pre><p>The best selling item and the sales month, and the best selling month for each item are required to be reported. The business request is converted to data requirements of retrieving the full row of the highest sales balance among all items and for each item.</p><h3>Solution 1</h3><p>The goal is to retrieve the eligible rows by matching the sales balance to the maximum sales balance. The <strong>common method</strong> is self-joining a subquery that calculates the maximum sales balance.</p><pre>select <br> t1.*<br>from table1 t1,<br> (select max(sale_balance) as max_bal from table1) t2<br>where t1.sale_balance = max_bal</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/417/1*5bNPOLsA8dqNdoI71c6Lmg.png" /><figcaption>Data1: Best selling item and month</figcaption></figure><p>The best selling item and month is item 1 in Mar23. Retrieving the best selling month per item requires both the item ids and the maximum sales balance of the item which can be calculated using a ‘<em>group by</em>’ clause in the subquery.</p><pre>select <br>  t1.*<br>from table1 t1,<br>(<br>    select <br>      id,<br>      max(sale_balance) as max_bal<br>    from table1<br>    group by 1<br>) t2<br>where t1.sale_balance = t2.max_bal<br>and t1.id = t2.id</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/417/1*EmECjQEMtfqKPpo_YhI9EA.png" /><figcaption>Data2: Best selling month per item</figcaption></figure><h3>Solution 2</h3><p>Instead of self-joining, there is no additional column required to append to the output from the subquery so that the joining condition can be placed in a ‘<em>where</em>’ statement.</p><p>The code to return date1 in solution 1 can be simplified as below.</p><pre>select <br> *<br>from table1<br>where sale_balance = (select max(sale_balance) from table1);</pre><p>However, the comparison can be done without the function <em>max(). </em>The <em>‘all’</em> operator allows self-comparison to sales balance in all rows.</p><pre><br>select <br> *<br>from table1<br>where sale_balance &gt;= all (select sale_balance from table1);</pre><p>Getting data2 requires to match by ids. The smaller values are removed from the output data by self-comparing using the ‘<em>exist</em>’ operator.</p><pre>select <br>  *<br>from table1 t1<br>where not exists <br>(<br>    select 1 from table1 t2<br>    where t1.id = t2.id<br>    and t1.sale_balance &lt; t2.sale_balance<br>)</pre><h3>Solution 3</h3><p>Getting the maximum value also can be achieved through getting the top 1 value after sorting the sales balance in a descending order. The SQL window function <em>row_number()</em> counts the order of the sorted data.</p><p>The ‘<em>partition by</em>’ clause is not necessary because the entire data is one partition. The ‘<em>qualify’</em> clause filters the unmatched rows after the window calculation to return data1.</p><pre>select *<br>from table1<br>qualify row_number() over (order by sale_balance desc) = 1</pre><p>The ‘<em>partition by</em>’ clause is required to calculate the maximum sales balance per item to return data2.</p><pre>select *<br>from table1 <br>qualify row_number() over (partition by id order by sale_balance desc) = 1</pre><h3>Solution 4</h3><p>The function <em>max()</em> can also be used as a window function which simplifies the codes in solution1 with the same logic.</p><p>The ‘<em>over</em>’ clause is required to enable using the function <em>max()</em> as a window function. 1 can be used to represent the entire data is one partition to return data1.</p><pre>select <br> *<br>from table1<br>qualify max(sale_balance) over (partition by 1) = balance;</pre><p>Extending the above code a bit can get data2.</p><pre>select <br> *<br>from table1<br>qualify max(sale_balance) over (partition by id) = balance;</pre><p>In conclusion, the most common method is self-joining a subquery with maximum calculation with or without ‘<em>group by’</em> clause. The function <em>max()</em> used as a window function simplifies the code along with the<em> qualify</em> clause.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6920d9388a54" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Joining two fields that require string transformation (Snowflake)]]></title>
            <link>https://medium.com/@vyvring/joining-two-fields-that-require-string-transformation-snowflake-beedc2855544?source=rss-ab6b8437d0a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/beedc2855544</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Vivian]]></dc:creator>
            <pubDate>Fri, 12 May 2023 07:57:55 GMT</pubDate>
            <atom:updated>2023-05-12T07:57:55.698Z</atom:updated>
            <content:encoded><![CDATA[<p>It is common that one or both fields required data transformation before using in an on clause to join two tables. One field in table 1 might contain only part of the string in table 2.</p><p>Assuming we sent a marketing campaign at the beginning of the month and expect to monitor the performance of the campaign. The mail-out campaign contains the campaign codes which the customers should provide during the enquiry to be eligible for the special offer. The business request is to calculate the response rate by date, which can be converted to a data requirement of table 1 left joining table2.</p><h3>Sample data</h3><p>Table1 is the mail-out campaign data, assuming the offer is sent to 5 customers.</p><pre>create temp table table1<br>(<br> campaign_id int,<br> campaign_code varchar(15),<br> sent_date date<br>);<br><br><br>insert into table1<br>values(1,&#39;1018&#39;,&#39;2023-04-03&#39;),<br>(2,&#39;1019&#39;,&#39;2023-04-03&#39;),<br>(3,&#39;1020&#39;,&#39;2023-04-03&#39;),<br>(4,&#39;1021&#39;,&#39;2023-04-03&#39;),<br>(5,&#39;1022&#39;,&#39;2023-04-03&#39;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*V46QqxYjHUANBJ-ZgKkL7w.png" /><figcaption>Campaign mail-out data</figcaption></figure><p>Table 2 is the response data, the campaign reference code contains a prefix. There are two responses.</p><pre>create temp table table2<br>(<br> app_id int,<br> create_date date,<br> reference_code varchar(15)<br>);<br><br>insert into table2<br>values(11,&#39;2023-04-23&#39;,&#39;AEP-1022&#39;),<br>(12,&#39;2023-04-28&#39;,&#39;AEP-1018&#39;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*lnL7XLO8MqG1hpvQGvzgkg.png" /><figcaption>Response data</figcaption></figure><p>The expected output data is as below, there are several ways to do it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*PigudrVqLrnDm0uFNInJ3Q.png" /><figcaption>Expected output data</figcaption></figure><h3>Solution1</h3><p>The goal is to have the reference code transformed to match the original campaign code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*n-YXO9zhafPwrLrDcGPckw.png" /><figcaption>Transformed Reference Code</figcaption></figure><h4>Method 1</h4><p>The function <em>substr()</em> is used to subtract 4 characters from the reference code from the 5th character.</p><pre>select <br> t1.*,<br> t2.create_date<br>from table1 t1<br>left join table2 t2 <br>on t1.campaign_code = substr(t2.reference_code,5,4);</pre><h4>Method2</h4><p>The function <em>split_part()</em> takes the 2nd part of the string by the delimiter dash ‘-’, which returns the same data as Method1.</p><pre>select <br> t1.*,<br> t2.create_date<br>from table1 t1<br>left join table2 t2 <br>on t1.campaign_code = split_part(t2.reference_code,&#39;-&#39;,2);</pre><h4>Method 3</h4><p>The regular expression function <em>regexp_replace()</em> removes all non-digits from the string, which returns the same data as the above two methods.</p><pre>select <br> t1.*,<br> t2.create_date<br>from table1 t1<br>left join table2 t2 <br>on t1.campaign_code = regexp_replace(t2.reference_code,&#39;[^0-9]&#39;,&#39;&#39;);</pre><h3>Solution 2</h3><p>Actually the transformation might not be necessary since there are ways to compare part of string.</p><h4>Method 4</h4><p>The function contains() matches the subset of the string. In our example, the campaign code is a subset string of the reference code.</p><pre><br>select <br> t1.*,<br> t2.create_date<br>from table1 t1<br>left join table2 t2 <br>on contains(t2.reference_code,t1.campaign_code);</pre><h4>Method 5</h4><p>The <em>like</em> operator matches campaign code to the last part of reference code, the prefix is represented by the wildcard ‘%’. The dash can be used to control where is the starting point to match the campaign code but in this case it is not neccessary.</p><pre>select <br> t1.*,<br> t2.create_date<br>from table1 t1<br>left join table2 t2 <br>on t2.reference_code like &#39;%-&#39;||t1.campaign_code</pre><h4>Method 6</h4><p>The function <em>endswith()</em> matches the tail of the reference code by the campaign code.</p><pre>select <br> t1.*,<br> t2.create_date<br>from table1 t1<br>left join table2 t2 <br>on endswith(t2.reference_code,t1.campaign_code)</pre><h3>Uncommon Solution</h3><p>The data imagination has no limit. In special situation, some functions can be used in an unusual way for particular shape of data. In our example, the campaign code is always 4-digit long and on which the prefix is added with dash to form the reference code.</p><h4>Method 7</h4><p>The position of the campaign code can be searched in the full length of the reference code. A dash can be added at the front as a control but it is not really necessary.</p><pre>select <br> t1.*,<br> t2.create_date<br>from table1 t1<br>left join table2 t2 <br>on position(&#39;-&#39;||t1.campaign_code,t2.reference_code,1)&gt;0</pre><h4>Method 8</h4><p>Using the similar logic, only the prefix is left if the 4-digit campaign code is removed from the reference code. We know the length of the prefix is 3.</p><pre>select <br> t1.*,<br> t2.create_date<br>from table1 t1<br>left join table2 t2 <br>on length(replace(t2.reference_code,&#39;-&#39;||t1.campaign_code,&#39;&#39;))=3</pre><p>In above solutions, the most commonly used is <em>substr()</em>. The <em>like</em> operator can fit more general situation if the prefix has dynamic length or the campaign code have different length of digits in the same data. It would be a better choice if the SQL efficiency is also a concern when SQL functions are used in the join conditions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=beedc2855544" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Wildcard Pattern Matching (SQL Server)]]></title>
            <link>https://medium.com/@vyvring/wildcard-pattern-matching-sql-server-4385d48d99bc?source=rss-ab6b8437d0a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/4385d48d99bc</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[sql-server]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Vivian]]></dc:creator>
            <pubDate>Thu, 27 Apr 2023 07:57:30 GMT</pubDate>
            <atom:updated>2023-04-27T07:57:30.484Z</atom:updated>
            <content:encoded><![CDATA[<p>There is a business case that two data from different data sources require to match by bank account number. The BSB is not recorded and some account numbers only have the last few digits. The bank names are not standardised, both data sources have its own standard of bank names.</p><p>The following data process is required to fully match two data:</p><ol><li>The bank names need to be standardised to compensate the missing BSB numbers.</li><li>The account numbers need to be matched by last couple digits in both directions.</li></ol><h3>Sample data</h3><pre>create table table1<br>(<br> lender varchar(50),<br> acctnumber varchar(50)<br>);<br><br>insert into table1 <br>values(&#39;St. George&#39;,&#39;1010293&#39;),<br>(&#39;St.George&#39;,&#39;1023934&#39;),<br>(&#39;ST George commercial &#39;,&#39;1139485&#39;),<br>(&#39;St George&#39;,&#39;239343&#39;),<br>(&#39;NAB Commericial&#39;,&#39;32903240801&#39;),<br>(&#39;NAB Business&#39;,&#39;32902390483&#39;),<br>(&#39;NAB Broekr&#39;,&#39;32903294845&#39;),<br>(&#39;NAB BROKER&#39;,&#39;39023894379&#39;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/293/1*aEdyPCFeNvVeT0Zfq-Ggzw.png" /><figcaption>Table 1</figcaption></figure><pre>create table table2<br>(<br> lender varchar(50),<br> loannumber varchar(50)<br>);<br><br>insert into table2<br>values<br>(&#39;St George&#39;,&#39;9881139485&#39;),<br>(&#39;St George&#39;,&#39;9881239343&#39;),<br>(&#39;NAB NPS and IIA&#39;,&#39;3894379&#39;),<br>(&#39;NAB&#39;,&#39;3294845&#39;),<br>(&#39;NAB Asset Finance&#39;,&#39;3240801&#39;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/1*0wM6ukqtWAffBHuAkpOZwQ.png" /><figcaption>Table 2</figcaption></figure><p>Note that the sample data is a perfect status. The real-world data could have last few digits matched but bank names unmatched.</p><h3>Solution</h3><p>Firstly, the lender names need to be standardised to allow two tables merging by lender.</p><p>The <strong>common solution</strong> is to use ‘case when’ clause to convert the lenders to a lender group. SQL server does not support regular expression. The LIKE operator can be used to find simple patterns. The code looks like below:</p><pre>select <br> *,<br> case when lender like &#39;St%George%&#39; then &#39;St George&#39;<br>   when lender like &#39;NAB%&#39; then &#39;NAB&#39;<br> end lender_group <br>from table2;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/1*CB3ohC75ZaWgRIe60urZ5g.png" /><figcaption>Grouping different lender names</figcaption></figure><p>The same ‘case when’ clause is used on table1 before joining two tables. Similar method is used to match loan numbers. The complete code is as below.</p><pre>select<br>  a.*,<br>  b.acctnumber<br>from <br>(<br>  select <br>    *,<br>    case <br>      when lender like &#39;St%George%&#39; then &#39;St George&#39;<br>      when lender like &#39;NAB%&#39; then &#39;NAB&#39;<br>    end lender_group <br>   from table2<br>) a<br>left join <br>(<br>  select <br>    *,<br>    case <br>      when lender like &#39;St%George%&#39; then &#39;St George&#39;<br>      when lender like &#39;NAB%&#39; then &#39;NAB&#39;<br>    end lender_group<br>   from table1<br>) b <br>on a.lender_group = b.lender_group<br>and (<br>     a.loannumber like &#39;%&#39;+ b.acctnumber <br>   or b.acctnumber like &#39;%&#39;+a.loannumber<br>);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/1*TYX8bBcR4KjGLwgHrhSMWw.png" /><figcaption>Matching output (method 1)</figcaption></figure><p>SQL server has limited functions to <strong>simplify above code</strong>. However, there is a similarity in above code that both tables have lender group calculation. Instead of using ‘case when’ clause, an explicit table can be created to do this job.</p><p>The lender names are separated by comma in a string. The function STRING_SPLIT can split them into rows.</p><pre>select value <br>from string_split(&#39;NAB,St George&#39;,&#39;,&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/138/1*FMwOBRUJLrxl6AKEMDFtSg.png" /><figcaption>Split a string to rows by a comma delimiter</figcaption></figure><p>Now table1 can left join the grouping table to translate lender names to a lender group. The pattern calculation is kept in the output data to show what the LIKE operator is searching.</p><pre>select <br> a.*,<br> b.value,<br> replace(b.value,&#39; &#39;,&#39;%&#39;)+&#39;%&#39; as pattern<br>from table1 a<br>left join string_split(&#39;NAB,St George&#39;,&#39;,&#39;) b<br>on a.lender like replace(b.value,&#39; &#39;,&#39;%&#39;)+&#39;%&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*l0AhjxBncUpR3wbz0MzKYg.png" /><figcaption>Output with patterns</figcaption></figure><p>The previous code can be simplified using the 3rd table.</p><pre>select<br>  a.*,<br>  c.value as lender_group,<br>  b.acctnumber<br>from test2 a<br>left join test1 b on (<br>   a.loannumber like &#39;%&#39;+ b.acctnumber <br> or b.acctnumber like &#39;%&#39;+a.loannumber<br>)<br>left join string_split(&#39;NAB,St George&#39;,&#39;,&#39;) c<br>on a.lender like replace(c.value,&#39; &#39;,&#39;%&#39;)+&#39;%&#39;<br>and b.lender like replace(c.value,&#39; &#39;,&#39;%&#39;)+&#39;%&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/1*_1l_swEMf81WZaKIESu45Q.png" /><figcaption>Matching output (Method 2)</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4385d48d99bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Credit products: BNPL, its uniqueness and differences to other credit products]]></title>
            <link>https://medium.com/@vyvring/credit-products-bnpl-its-uniqueness-and-differences-to-other-credit-products-4c33d8f171a5?source=rss-ab6b8437d0a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c33d8f171a5</guid>
            <category><![CDATA[risk-management]]></category>
            <category><![CDATA[credit]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Vivian]]></dc:creator>
            <pubDate>Mon, 17 Apr 2023 07:56:48 GMT</pubDate>
            <atom:updated>2023-04-17T07:56:48.370Z</atom:updated>
            <content:encoded><![CDATA[<p>The consumer BNPL product is advertised as a new form of credit facility and introduced around 2019- 2021 in Australia. In fact, in Australia and New Zealand, the earliest BNPL product embedded with a credit card is GEM credit card (by former GE Capitial) launched in 2013. Paypal’s BNPL feature is another classic BNPL facility introduced in 2020.</p><p>A classic BNPL product is a capped credit facility that splits large amount of purchase to several monthly instalments up to 60 months (equivalent to 5-year term loan).</p><h3>Product features</h3><h4>Fees and interest</h4><p>The classic BNPL product does not charge settlement fee and instalment fee. It charges late payment fee and the deferred interest will be charged on full owed amount if there is any instalment payment delayed.</p><p>The nowadays BNPL like products (advertised as an alternative of a credit card) charge settlement fee, per instalment transaction fee, account management fees (some allows minimum monthly payment to charge this fee), and late payment fee. Adding up of these fees together, these BNPL like products are not interest free. The interest charge has been converted to the fees.</p><h4>Term and payment frequency</h4><p>The benefit of a classic BNPL product is it can help to reduce spike of financial cash flow and smooth out the big spending to several months. For example, A $10,000 credit borrowing of a purchase of a diamond ring can be split to 12-month instalments on BNPL facility, which is more convenience and cheaper than applying for a personal loan or paying by a common credit card.</p><p>The nowadays BNPL like products shorten the term to weeks which lose the cash flow management functionality. Using credit card would have been a better choice than choosing a BNPL like product since a credit card has 55 days interest free period, or a special credit card (like GEM credit card) has 6-month interest free period.</p><h4>Payments</h4><p>In a classic BNPL product, each payment paid by the customer is split to each purchase‘s instalment payments. The split of instalment payments was manually done back to the old days. For example, the customer who made two purchases on a BNPL facility would need to call in call centre to allocate his payment. Nowadays, an advance IT system could automatically distribute the payments to different instalments for different purchases. Most of the time, the customer would have only one BNPL borrowing on the facility since one big purchase would have used up most of the credit facility. It is unnecessary to use a BNPL facility for daily shopping.</p><p>The nowadays BNPL like products split small purchases to instalments by weeks, the payment charged monthly, or some products allow minimum monthly payment mimicking a credit card and it is not interest free while account fees are applicable. A $10 monthly account fee on $500 limit is 2% interest per month and 24% annually (the fee won’t accrue interest so that the annual rate is a simple interest rate).</p><h4>Profit/Revenue</h4><p>Any credit products need to make incomes. The income is fee and interest.</p><p>A classic BNPL earns income from merchant fee, or transaction fee from Mastercard/Visa if the facility is on a credit card. The late payment and deferred accrued interest are charged to cover the operational expenditure while the account is in arrears.</p><p>The nowadays BNPL like products earn from merchant fee, settlement fee per purchase, convenience fee per instalment (charges for setting up per direct debit), account fee. The late payment or other collection fees are charged if the account is in arrears. The late payment fee will charge if a direct debit charged is failed, regardless it is accidental or purposed.</p><h3>Difference to other products</h3><h4>Credit card and overdraft</h4><p>A classic BNPL product has a limit facility which is similar to a credit card or overdraft facility of a transaction account.</p><p>The difference to a credit card is that a classic BNPL product pays by instalments, it does not have a minimum monthly payment concept and does not need to pay off the full statement amount to keep the interest free feature during the payment period.</p><p>The difference to an overdraft facility is that the overdraft facility has monthly fee as a facility holding cost and the interest is charged once amount is withdrawn from the facility.</p><p>A key difference to any credit card or overdraft facility is that a classic BNPL product has its merchant partners where the main income should be come from these partnerships. The BNPL like products earn income from both merchants and consumers.</p><h4>Term loan</h4><p>A classic BNPL product has its term of repayment which is similar to a term loan. It is more than a term loan because each purchase could be considered a mini term loan within a capped credit facility.</p><p>Another difference is a classic BNPL loan only needs to pay back the principal but a term loan’s repayment consists of principal payment and interest payment at the same time.</p><h3>Conclusion</h3><p>In conclusion, a classic BNPL product has its unique characteristics. The unique product design is not only for both consumer and merchant partners’ benefits, but also for contributing to its specific risk management that is very different to other credit products.</p><p>For consumer perspective, a classic BNPL product could help to manage cash flow if used wisely. For example, Paypal’s ‘Pay in 4’ can extend a payment to 4 fortnightly payments which is possible to add to 2-3 different interest-free periods on a 55-day interest free credit card. It would help a bit if you want to manage your expenditure well during the months that you need to pay for every living expenditures altogether unfortunately, for example, utilities, insurances, car registration, school fee etc.</p><p>Other BNPL like products provide an easy access to credit but actually are quite costly. A low limit, low-interest, fee-free, 55-day interest free credit card would be a much better choice.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c33d8f171a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Preserve information during data reduction]]></title>
            <link>https://medium.com/@vyvring/preserve-information-during-data-reduction-2ca1f9c5d01c?source=rss-ab6b8437d0a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ca1f9c5d01c</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Vivian]]></dc:creator>
            <pubDate>Tue, 14 Mar 2023 06:56:43 GMT</pubDate>
            <atom:updated>2023-03-14T06:56:43.863Z</atom:updated>
            <content:encoded><![CDATA[<p>The data reduction has been discussed in article <a href="https://medium.com/@vyvring/compressing-data-by-time-frequency-in-sql-db82da02f921?source=your_stories_page-------------------------------------">Compressing data by time frequency in SQL</a>.</p><p>The design logic is to form a group by defining a common date for a series of dates, then keep the newest record within the group. Using this method, the information of the uncollected rows are completely ignored.</p><h3>Business case</h3><blockquote>The daily average unpaid balance is required for a financial metric. Assuming the figure is required for a monthly report.</blockquote><h4>Sample data</h4><p>A few more columns are added into the <em>sample_loan_info</em> data used in previous article.</p><pre>create or replace temp table sample_loan_info<br>(<br> loan_id int,<br> funded_date date,<br> funded_amount numeric(10,2),<br> payment_amount numeric(10,2),<br> frequency varchar(20)<br>);<br><br>insert into sample_loan_info<br>values (1,&#39;2022-12-28&#39;,10000,200,&#39;Weekly&#39;),<br>(2,&#39;2023-01-20&#39;,5000,150,&#39;Weekly&#39;),<br>(3,&#39;2023-02-04&#39;,2000,100,&#39;Weekly&#39;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*nBl8jUi-6LhypJHVvVMQkA.png" /><figcaption>Loan information table</figcaption></figure><p>The <em>sample_snapshot</em> data is expanded to add the unpaid balance that is simulated by the payment frequency. Assuming all payments were collected on time.</p><pre>create or replace temp table sample_snapshot as <br>select <br>  a.as_of_date,<br>  l.loan_id,<br>  l.funded_date,<br>  l.funded_amount - <br>  floor((a.as_of_date -l.funded_date)/7)*l.payment_amount as unpaid_balance<br>from <br>(<br>  select <br>    current_date-seq4() as as_of_date<br>   from table(generator(rowcount=&gt;70))<br>   where dayofweek(as_of_date) not in (6,0)<br>) a<br>left join sample_loan_info l on a.as_of_date &gt;= l.funded_date<br>order by 1,2;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*fnVOg53kx9B3bSWjCn0_6w.png" /><figcaption>Part of daily snapshot</figcaption></figure><h3>Solution</h3><p>Snowflake always do a full table scan. Filtering data using the date series calculated by the daily snapshot itself scans the daily snapshot twice. It is more efficient to use only one scan to complete the task.</p><h4><strong>Step 1. filtering by window function</strong></h4><p>The unwanted rows can be removed after extracting the full daily data within required time frame. The benefit of doing so is that more details are kept in the initial data extraction which may be useful for some additional calculations.</p><p>Firstly, the next <em>as_of_date</em> is obtained through the ‘<em>lead</em>’ function by the partition of the month group calculated by the function <em>last_day</em> and loan id.</p><pre>select <br> *,<br> last_day(as_of_date) as end_of_month,<br> lead(as_of_date) over (partition by loan_id,end_of_month order by as_of_date) as next_as_of_date<br>from sample_snapshot<br>order by as_of_date</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*KZZXadlgXJ7DdSLllYpbdg.png" /><figcaption>NULL value at the edge of a month group</figcaption></figure><p>The ‘<em>qualify</em>’ clause can be used directly on the competed values of the window function. The last day within a month group is identified by checking if it has the next day in the same month. The last day of the month can be directly filtered in the ‘<em>partition by</em>’ clause.</p><pre>select <br> *<br>from sample_snapshot<br>qualify lead(as_of_date) over (partition by loan_id,last_day(as_of_date) order by as_of_date) is null<br>order by as_of_date,loan_id;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*t6MqwSivsCXQJ0yMi7q61Q.png" /><figcaption>Monthly snapshot for each month</figcaption></figure><p>Mar23 is an incomplete month in our simulation so that the maximum date in Mar23 is 10Mar23.</p><h4><strong>Step 2. calculate the daily average</strong></h4><p>We will ignore the missing weekend data in this sample, assuming the daily unpaid balance only taken into account the weekday.</p><p>The qualify clause is executed on computed window function output so that the average function can be used on the daily unpaid balance before the rest of the rows besides the end of month are removed.</p><p>The function <em>avg</em> can be used in window calculation, it returns the average within the partition by default.</p><pre>select <br> *,<br> last_day(as_of_date) as end_of_month,<br> avg(unpaid_balance) over (partition by loan_id,end_of_month) as avg_unpaid_balance,<br> lead(as_of_date) over (partition by loan_id,end_of_month order by as_of_date) as next_as_of_date<br>from sample_snapshot<br>where loan_id = 2<br>order by loan_id,as_of_date;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HdF5wf0c9FzaAdCuQ2rn7A.png" /><figcaption>Data before filtering</figcaption></figure><p>Finalise the code by adding average calculation:</p><pre>select <br> *,<br> avg(unpaid_balance) over (partition by loan_id,last_day(as_of_date)) as avg_unpaid_balance<br>from sample_snapshot<br>qualify lead(as_of_date) over (partition by loan_id,last_day(as_of_date) order by as_of_date) is null<br>order by as_of_date,loan_id;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*PeMq6wTY4aP4zKQdahUl_A.png" /><figcaption>Monthly snapshot with average balance</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ca1f9c5d01c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data terminology — data shapes]]></title>
            <link>https://medium.com/@vyvring/data-terminology-data-shapes-d9ac0cb7d67d?source=rss-ab6b8437d0a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9ac0cb7d67d</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-analytics]]></category>
            <dc:creator><![CDATA[Vivian]]></dc:creator>
            <pubDate>Mon, 13 Mar 2023 06:56:49 GMT</pubDate>
            <atom:updated>2023-03-13T06:56:49.832Z</atom:updated>
            <content:encoded><![CDATA[<h3>Data terminology — data shapes</h3><p>In data career, you might constantly hear people speak with lots of data acronyms or technical terms that you have no clue what they are talking about. You might be afraid of asking them or interrupt the conversation to ask a question because it might make you look unprofessional.</p><p>Using big words does not mean the speakers fully understand them. They might hear them from someone and repeated the words in a conversation, or if they did it intentionally, they might face sharp questions from the audiences who understand the terminology. An experience data professional with good communication skills would avoid the big words and use plain language to make a smooth conversation.</p><p>I will go through a few common data terminologies to prepare you for such conversation. It could help you to spot true professionals who are worth to maintain a good business relationship in order to help you advance your career in future.</p><h3>Data shapes</h3><p>In data world, there are terminologies to describe data shapes. Some words are derived from mathematics terms.</p><h4>Scalar</h4><p>The word ‘<em>scalar</em>’ is derived from mathematics. A scalar is a real number or in more general term an element of a field in a vector, used in linear algebra to describe vector and matrix.</p><p>In data world, the meaning has been extended. A scalar data is a single data value, which can be a number, a character, a time, a date etc. as long as it occupies only one field in the data.</p><p>Since it only occupies one field, some special data types for unstructured data in data world are considered as a scalar data as well. For example, an array, an object, a variant, a big text field storing JSON structure structure etc.</p><p>The examples of a JSON object can be found in my previous articles:</p><ol><li><a href="https://medium.com/@vyvring/create-a-state-dimension-table-in-one-sql-e3292d6adecb?source=your_stories_page-------------------------------------">Create a state dimension table in one SQL</a></li></ol><p>The examples of an array can be found in my previous articles:</p><ol><li><a href="https://medium.com/@vyvring/the-concept-of-looping-equivalence-in-sql-4d7f821c6c47?source=your_stories_page-------------------------------------">The concept of looping equivalence in SQL</a></li><li><a href="https://medium.com/@vyvring/pairing-data-using-arrays-in-sql-e82d8b62c14?source=your_stories_page-------------------------------------">Pairing data using arrays in SQL</a></li></ol><h4>Tuple</h4><p>A tuple is a mathematical term as well. The original meaning in mathematics is a finite ordered sequence. In data world, it refers to a data row with multiple columns.</p><h4>Tabular</h4><p>A tabular is a technical term only used in the data world. It refers to a data with multiple rows and columns.</p><h3>SQL function types</h3><p>Two of above data terms are usually used to categorise types of a SQL function by the shape of the return dataset.</p><h4>Scalar function</h4><p>Most of the SQL functions return a <strong>scalar</strong> data. However a data table can be wrapped into an unstructured data to meet the criteria of a scalar return value. Below is a list of SQL scalar functions used in my previous articles.</p><p><strong>seq4(), dayofweek(), last_day(), dayname(), date_trunc():</strong></p><ol><li><a href="https://medium.com/@vyvring/calculate-the-end-of-the-week-in-sql-9f4cef429eb1?source=your_stories_page-------------------------------------">Calculate the end of the week in SQL</a></li><li><a href="https://medium.com/@vyvring/create-a-user-defined-function-to-calculate-the-last-day-of-the-week-5813ef52f7fd?source=your_stories_page-------------------------------------">Create a user-defined function in SQL to calculate the last day of the week</a></li></ol><p><strong>regexp_replace(), regexp_substr():</strong></p><ol><li><a href="https://medium.com/@vyvring/the-concept-of-looping-equivalence-in-sql-4d7f821c6c47?source=your_stories_page-------------------------------------">The concept of looping equivalence in SQL</a></li><li><a href="https://medium.com/@vyvring/extract-a-state-abbreviation-and-replace-by-the-full-state-name-with-regex-dbd80b29c59?source=your_stories_page-------------------------------------">Extract a state abbreviation and replace by the full state name with regex</a></li><li><a href="https://medium.com/@vyvring/extract-a-full-state-name-and-replace-by-the-state-abbreviation-with-regex-36b0c9b07e?source=your_stories_page-------------------------------------">Extract a full state name and replace by the state abbreviation with regex</a></li></ol><p>A scalar function is usually placed in the ‘select’ statement:</p><pre>select scalar_func();</pre><h4>Table function</h4><p>A SQL function returning a <strong>tabular</strong> data is called a <strong>SQL table function</strong>. Below is a list of SQL table functions used in my previous articles.</p><p><strong>generator():</strong></p><ol><li><a href="https://medium.com/@vyvring/calculate-the-end-of-the-week-in-sql-9f4cef429eb1?source=your_stories_page-------------------------------------">Calculate the end of the week in SQL</a></li></ol><p><strong>flatten():</strong></p><ol><li><a href="https://medium.com/@vyvring/create-a-state-dimension-table-in-one-sql-e3292d6adecb?source=your_stories_page-------------------------------------">Create a state dimension table in one SQL</a></li><li><a href="https://medium.com/@vyvring/efficient-join-avoid-joining-same-table-multiple-times-370a3efdd387?source=your_stories_page-------------------------------------">Efficient join — avoid joining same table multiple times</a></li></ol><p><strong>unpivot():</strong></p><ol><li><a href="https://medium.com/@vyvring/the-concept-of-looping-equivalence-in-sql-4d7f821c6c47?source=your_stories_page-------------------------------------">The concept of looping equivalence in SQL</a></li></ol><p>A table function is usually placed in the ‘from’ statement. In Snowflake the function <em>table()</em> is required to call a table function.</p><pre>select ...<br>from table(table_func())</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9ac0cb7d67d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Use grouping sets to do multiple summaries at once]]></title>
            <link>https://medium.com/@vyvring/use-grouping-sets-to-do-multiple-summaries-at-once-6984053bd1b0?source=rss-ab6b8437d0a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/6984053bd1b0</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Vivian]]></dc:creator>
            <pubDate>Fri, 10 Mar 2023 06:56:42 GMT</pubDate>
            <atom:updated>2023-03-10T06:56:42.110Z</atom:updated>
            <content:encoded><![CDATA[<h3>Business case</h3><blockquote>Using different angles to measure the sales historical performance, by sales agent or by account owners</blockquote><h4>Data background</h4><p>The same deals could have an account owner different to the sales agent made the deal. The reason of it has been covered in article <a href="https://medium.com/@vyvring/recover-and-consolidate-the-historical-field-changes-in-snowflake-sql-f7e61f447a84?source=your_stories_page-------------------------------------">Recover and consolidate the historical field changes in SQL</a>.</p><p>The historical performance is measured by conversion rate.</p><p>The <strong>conversion rate</strong> could be any conversion from lead to application ratio or by business definition in different companies, the application to funded ratio. The lead to application ratio is usually used by marketing performance.</p><p>The formula is as below:</p><pre>sum(funded_count)/sum(application_count) as conversion_rate</pre><h4>Sample data</h4><pre>create table sample_application<br>(<br>  app_id int,<br>  create_date date,<br>  sales_agent varchar(20),<br>  owner varchar(20),<br>  approved boolean,<br>  funded boolean<br>);<br><br>insert into sample_application<br>values (1,&#39;2023-01-10&#39;,&#39;Mark L.&#39;,&#39;Mark L.&#39;, true,false),<br>(2,&#39;2023-01-24&#39;,&#39;Kerry A.&#39;,&#39;Mark L.&#39;,true,true),<br>(3,&#39;2023-02-07&#39;,&#39;Kerry A.&#39;,&#39;Kerry A.&#39;,true,false),<br>(4,&#39;2023-02-10&#39;,&#39;Mark L.&#39;,&#39;Mark L.&#39;,true,true),<br>(5,&#39;2023-02-15&#39;,Kerry A.&#39;,&#39;Kerry A.&#39;,true,true);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*9LYFrkd4WW-Xwc_3ScTzyQ.png" /><figcaption>Sample source data</figcaption></figure><p>In real data, the data warehouse might only store users as IDs, the method to retrieve multiple users’ names at once was discussed in article <a href="https://medium.com/@vyvring/efficient-join-avoid-joining-same-table-multiple-times-370a3efdd387?source=your_stories_page-------------------------------------">Efficient join — avoid joining same table multiple times</a>.</p><p>In this article, we assume that the user names have already been retrieved to keep the SQL simple.</p><h3>Solution</h3><p>The conversion rate needs to be summarised by month and sales agents, or by month and account owners. Two different ‘group by’ queries can do the job.</p><ol><li>Summarised by month and sales agents:</li></ol><pre>select <br>  date_trunc(&#39;month&#39;,create_date) as reporting_month,<br>  sales_agent,<br>  sum(funded::int)/count(app_id)*100 as conversion_rate<br>from sample_application<br>group by 1,2;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*AMWVUf_LFx4YNSJhaWkOtg.png" /></figure><p>2. Summarised by month and account owners:</p><pre>select <br>  date_trunc(&#39;month&#39;,create_date) as reporting_month,  <br>  owner,<br>  sum(funded::int)/count(app_id)*100 as conversion_rate<br>from sample_application<br>group by 1,2;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/1*4mkIyztwNP_z4nQTp7xPTg.png" /></figure><p><strong>Note</strong>: both conversion rates times 100 to show as percentage.</p><p>However we might want to export as a data to excel or visualization software. It would be better to export as one single data. Surely we can do a ‘union all’ join to append one data to another. A ‘group_name’ field is added to categorise the ‘sales agent’ and ‘account ower’ reports.</p><pre>select <br>  date_trunc(&#39;month&#39;,create_date) as reporting_month,<br>  &#39;Sales Agent&#39; as group_name,<br>  sales_agent as agent_name,<br>  sum(funded::int)/count(app_id)*100 as conversion_rate<br>from sample_application<br>group by 1,2,3<br>union all <br>select <br>  date_trunc(&#39;month&#39;,create_date) as reporting_month, <br>  &#39;Account owner&#39; as group_name,<br>  owner as agent_name,<br>  sum(funded::int)/count(app_id)*100 as conversion_rate<br>from sample_application<br>group by 1,2,3;<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*Cf-SqQkyBK0kMrCIvYKHUQ.png" /><figcaption>Output from union join</figcaption></figure><p>The grouping sets can combine three steps of the above data operations into one query.</p><pre>select <br>  date_trunc(&#39;month&#39;,create_date) as reporting_month,<br>  sales_agent,<br>  owner,<br>  sum(funded::int)/count(app_id)*100 as conversion_rate<br>from sample_application<br>group by grouping sets (<br>  (reporting_month,sales_agent),(reporting_month,owner)<br>);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*90dQk_TFCgVNUpLY27T2Lg.png" /></figure><p>There are NULL values in ‘sales agent’ and ‘owner’ columns which can be combine to one column in the final data output:</p><pre>select <br>  date_trunc(&#39;month&#39;,create_date) as reporting_month,<br>  case when sales_agent is not null then &#39;Sales Agent&#39;<br>      else &#39;Account Owner&#39; end as group_name,<br>  coalesce(sales_agent,owner) agent_name,<br>  sum(funded::int)/count(app_id)*100 as conversion_rate<br>from sample_application<br>group by grouping sets (<br>  (reporting_month,sales_agent),(reporting_month,owner)<br>);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*BgWXQ8U4wt0QwKUahEZCTQ.png" /><figcaption>Output from grouping sets</figcaption></figure><h3>Extension of the report:</h3><p>We can extend the code a bit further to cover the summary of the month as the total sum of the sales agent or owner group. Firstly, we view the raw output without the modifying the each group columns:</p><pre>select <br>  date_trunc(&#39;month&#39;,create_date) as reporting_month,<br>  sales_agent,<br>  owner,<br>  sum(funded::int)/count(app_id)*100 as conversion_rate<br>from sample_application<br>group by grouping sets (<br>  reporting_month,(reporting_month,sales_agent),(reporting_month,owner)<br>);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*ZujPrcv4hBQ1rTDyb6NNeg.png" /></figure><p>Both sales_agent and Owner columns are NULL for the monthly summaries. The final code for report output needs to be adjusted.</p><pre>select <br>  date_trunc(&#39;month&#39;,create_date) as reporting_month,<br>  case when sales_agent is not null then &#39;Sales Agent&#39;<br>      when owner is not null then &#39;Account Owner&#39;<br>      else &#39;Total&#39; end as group_name,<br>  coalesce(sales_agent,owner) agent_name,<br>  sum(funded::int)/count(app_id)*100 as conversion_rate<br>from sample_application<br>group by grouping sets (<br>  reporting_month,(reporting_month,sales_agent),(reporting_month,owner)<br>);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*Pg20jAFSmOnhsaptmnzCiw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6984053bd1b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Extract a full state name and replace by the state abbreviation with regex]]></title>
            <link>https://medium.com/@vyvring/extract-a-full-state-name-and-replace-by-the-state-abbreviation-with-regex-36b0c9b07e?source=rss-ab6b8437d0a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/36b0c9b07e</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Vivian]]></dc:creator>
            <pubDate>Thu, 09 Mar 2023 06:56:42 GMT</pubDate>
            <atom:updated>2023-03-09T06:56:42.516Z</atom:updated>
            <content:encoded><![CDATA[<p>In last article, a state abbreviation is converted to the full state name. It is important to define the surrounding text to correctly extract the string pattern.</p><p>Another solution is to convert a full state name back to the abbreviation. The pattern becomes more comprehensive since the full state name could have one word, 2 words or 3 words. However it would allow easier coding to split suburb, state, postcode or country afterwards.</p><h4>From full state name to an abbreviation</h4><p>The pattern needs to be more precise since the state name could be a road name, for example, ‘Victoria road’. The trick of adding a space alone around a grouping of state names in last article won’t work.</p><p>The postcode is right behind the state name which can be a good reference text closer to the string pattern.</p><p>There is a comma (,) instead of a space separating suburb and state name in the last row of the input data, which needs to be added as part of the searching condition. It is a single character so that [] square parentheses are used.</p><pre>regexp_substr(address,<br>&#39;[, ](Northern Territory|New South Wales|Western Australia|Victoria) \\d{4}&#39;,<br>1,1,&#39;ie&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/1*tZHVFhJuatyUofbIs_4XcA.png" /></figure><p>We can’t do a loop like in other programming languages to search the correct key by value in an object. To simplify the issue, our data source could be used to create a different JSON object using the full state names as keys and the abbreviations as values.</p><p>The dimension table is built in article: <a href="https://medium.com/@vyvring/create-a-state-dimension-table-in-one-sql-e3292d6adecb?source=your_stories_page-------------------------------------">Create a state dimension table in one SQL</a>.</p><pre>select <br>  object_agg(state_name,state_abbrv::variant) as full_search<br>from Dim_Australia_State</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*4erCgHVRNErQ8Om-kAtSjQ.png" /><figcaption>Different Key and Value</figcaption></figure><pre>full_search[full_str]::string as abbrv_str</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*cMwUmjZtUdlEHPI-dz2ZLQ.png" /></figure><p>The complete list of full state name is quite long, but they can be obtained from the state dimension table as well.</p><pre>select <br> listagg(state_name,&#39;|&#39;) as full_list<br>from Dim_Australia_State</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*xpoLHpy_nGo9zzVMBBmq2g.png" /></figure><p>The replaced pattern is more complex. The surrounding text needs to be added back to the replaced value. The ‘\\1’ and ‘\\3’ are the content extracted from the first and the third parentheses.</p><pre>regexp_replace(address,&#39;([, ])(&#39;||full_list||&#39;)( \\d{4})&#39;, &#39;\\1&#39;||abbrv_str||&#39;\\3&#39;,1,1,&#39;i&#39;)</pre><p>The full code is as below:</p><pre>select <br>  value::string as address,<br>  regexp_substr(address,&#39;[, ](&#39;||full_list||&#39;) \\d{4}&#39;,1,1,&#39;ie&#39;) as full_str,<br>  full_search[full_str]::string as abbrv_str,<br>  regexp_replace(address,&#39;([, ])(&#39;||full_list||&#39;)( \\d{4})&#39;, &#39;\\1&#39;||abbrv_str||&#39;\\3&#39;,1,1,&#39;i&#39;) as updated_address<br>from lateral flatten(input=&gt;<br> [&#39;1 Sydney Street, Sydney NSW 2137&#39;,<br> &#39;1 Sydney Street, Sydney New South Wales 2137&#39;,<br> &#39;111 Nation Crescent, Coconut Grove NT 0810&#39;,<br> &#39;111 Nation Crescent, Coconut Grove Northern Territory 0810&#39;,<br> &#39;18 Victoria Avenue, Perth Western Australia 2111&#39;,<br> &#39;18 Victoria Avenue, Perth WA 2011&#39;,<br> &#39;22 Western Street, Geelong West,Victoria 3218&#39;,<br> &#39;12 Western Street, Geelong West VIC 3218&#39;]) a,<br> (<br>   select <br>     object_agg(state_name,state_abbrv::variant) as full_search,<br>     listagg(state_name,&#39;|&#39;) as full_list<br>   from Dim_Australia_State<br> ) b<br>;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*dTZETUlAGefLQkug87o97A.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36b0c9b07e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>