<?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 Ramdosk on Medium]]></title>
        <description><![CDATA[Stories by Ramdosk on Medium]]></description>
        <link>https://medium.com/@ramdosk92?source=rss-3d44b7a76dc9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*1fNKKkKDhs91vPXCjnmIcQ@2x.jpeg</url>
            <title>Stories by Ramdosk on Medium</title>
            <link>https://medium.com/@ramdosk92?source=rss-3d44b7a76dc9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 13:40:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ramdosk92/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[How Can You Display a Numeric Metric from One CRM Analytics Dataset on Records from Another Dataset…]]></title>
            <link>https://ramdosk92.medium.com/how-can-you-display-a-numeric-metric-from-one-crm-analytics-dataset-on-records-from-another-dataset-6976f8073f4f?source=rss-3d44b7a76dc9------2</link>
            <guid isPermaLink="false">https://medium.com/p/6976f8073f4f</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[saql]]></category>
            <category><![CDATA[crm-analytics]]></category>
            <category><![CDATA[data-modeling]]></category>
            <category><![CDATA[window-functions]]></category>
            <dc:creator><![CDATA[Ramdosk]]></dc:creator>
            <pubDate>Tue, 24 Nov 2026 17:55:55 GMT</pubDate>
            <atom:updated>2026-11-24T17:55:55.274Z</atom:updated>
            <content:encoded><![CDATA[<h3>How Can You Display a Numeric Metric from One CRM Analytics Dataset on Records from Another Dataset — While Preserving Granularity and Avoiding Circular Recipe Dependencies?</h3><p>Using SAQL union and window functions to enrich row-level records without cogroup aggregation or recipe loops.</p><h3>The Problem</h3><p>In Salesforce CRM Analytics, a common data-modeling challenge shows up whenever <strong>Dataset C </strong>computes a custom numeric score (such as a health score, risk index, or composite rating) using data from <strong>Dataset A</strong>, <strong>Dataset B </strong>and you later need to display that numeric metric alongside individual, granular records from <strong>Dataset A</strong> &amp; <strong>Dataset B </strong>in a dashboard list.</p><p>Normally, you might consider two standard approaches — and both run into trouble here:</p><ul><li><strong>Bringing Dataset B into Dataset A’s Recipe:</strong> Because Dataset C already depends on Dataset A &amp; B to calculate the score, pulling Dataset C back into Dataset A’s &amp; B’s recipe creates a circular dependency.</li><li><strong>Using </strong><strong>cogroup in SAQL:</strong> Co-grouping across datasets with different grains aggregates records together, which breaks the row-level granularity needed when displaying individual items as they are.</li></ul><h3><strong>Scenario:</strong></h3><p>Suppose a team wants a consolidated daily list showing <strong>open support tickets</strong>, <strong>today’s open events and tasks</strong>, and <strong>opportunities closing today</strong> — and each row needs to display its associated <strong>Account Health Score</strong>.</p><h3>Approach:</h3><p>To solve this cleanly at query time without touching upstream recipe dependencies or losing row-level detail, we use a <strong>Schema Alignment + union + Window Function Broadcast</strong> pattern:</p><ol><li><strong>Normalize Streams onto a Shared Schema:</strong> Project each source stream ( Parent, StreamA, StreamB) with the same column set and compatible data types.</li><li><strong>Preserve Granularity with a Unique Record Key:</strong> Include a unique record identifier (RecordId) in the grouping grain so individual records never collapse into one another.</li><li><strong>Broadcast the Numeric Metric via Window Function:</strong> Set the numeric metric to 0 on record streams and its actual value on the parent metric stream, union them, and apply sum(sum(‘Metric’)) over ([..] partition by ‘ParentId’).</li><li><strong>Filter Out Helper Rows:</strong> Remove the synthetic parent rows at the end (‘Type’ != “Parent”) so only the target records remain in the UI.</li></ol><h3>Step-by-Step Logic</h3><h4>Step 1 — Prepare the Parent Metric Stream</h4><p>Load the dataset holding the calculated numeric metric and project it with &#39;ParentId&#39;, the numeric metric column, and placeholder values for the list columns so its schema matches the other streams.</p><pre>Account = load &quot;AccountDataset&quot;;<br>Account = foreach Account generate &#39;Id&#39; as &#39;Account Id&#39;, &quot;-&quot; as &#39;Title&#39;, &quot;Account&quot; as &#39;Type&#39;, &quot;-&quot; as &#39;Date&#39;, &#39;Account_Health&#39; as &#39;Account_Health&#39;, &quot;-&quot; as &#39;Dummy id&#39;, &quot;-&quot; as &#39;Status&#39;;</pre><h4>Step 2 — Filter and Project the First Record Stream</h4><p>Load the first record dataset (for example, open follow-up Activities(Event &amp; Task), apply your business filters, and project the shared fields with &#39;Metric&#39; = 0 and a unique record ID so every individual record stays distinct.</p><pre>Activity = load &quot;ActivitiesDataset&quot;;<br>Activity = filter Activity by (&#39;Status&#39; != &quot;Completed&quot; || &#39;Status&#39; is null);<br>Activity = filter Activity by date(&#39;ActivityDate_Year&#39;, &#39;ActivityDate_Month&#39;, &#39;ActivityDate_Day&#39;) in[&quot;current day&quot;..&quot;current day&quot;];<br>Activity = foreach Activity generate &#39;Account_Dynamic_Id&#39; as &#39;Account Id&#39;,&#39;Subject&#39; as &#39;Title&#39;,&#39;Activity_Type&#39; as &#39;Type&#39;,&quot;Today&quot; as &#39;Date&#39;,0 as &#39;Account_Health&#39;, &#39;Id&#39; as &#39;Dummy id&#39;,<br>(case when &#39;Activity_Type&#39; == &quot;Event&quot;<br>    then &#39;Meeting_Status&#39;<br>    when &#39;Activity_Type&#39; == &quot;Task&quot;<br>    then &#39;Status&#39;<br>end) as &#39;Status&#39;;</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*nFhUQ20JxC4A0uR8ttUYvw.png" /><figcaption>first stream output</figcaption></figure><h4>Step 3 — Filter and Project Additional Record Streams</h4><p>Load any additional record datasets (for example,Opportunities Closing Today ), apply their filters, and project them onto the exact same column names, order, and data types with &#39;Metric&#39; = 0 and their unique record ID.</p><pre>Opportunity = load &quot;OpportunityDataset&quot;;<br>Opportunity = filter Opportunity by date(&#39;CloseDate_Year&#39;, &#39;CloseDate_Month&#39;, &#39;CloseDate_Day&#39;) in [&quot;current day&quot;..&quot;current day&quot;];<br>Opportunity = filter Opportunity by &#39;StageName&#39; not in[&quot;Closed Won&quot;, &quot;Closed Lost&quot;];<br>Opportunity = foreach Opportunity generate &#39;AccountId&#39; as &#39;Account Id&#39;,&#39;Name&#39; as &#39;Title&#39;,&quot;Opportunity&quot; as &#39;Type&#39;,&quot;Today&quot; as &#39;Date&#39;, 0 as &#39;Account_Health&#39;, &#39;Id&#39; as &#39;Dummy id&#39;, &#39;StageName&#39; as <br>&#39;Status&#39;;</pre><p>Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*PiAzTR8UnlV_CHGCaVuS0A.png" /><figcaption>2nd stream output</figcaption></figure><blockquote>additional datasets like Cases/Support Tickets follow the exact same projection pattern.</blockquote><h4>Step 4 — Union, Group at Record Grain, and Broadcast the Metric</h4><p>Union all streams, group by all projected dimensions (including the unique record key so individual rows never merge), and use <strong>sum(sum(‘Metric’)) over ([..] partition by ‘ParentId’) </strong>to stamp every matching child record with the parent metric while keeping row-level granularity.</p><p><strong>How the Window Function Works (and Why It Matters):</strong></p><ul><li><strong>Inner </strong><strong>sum (Group Aggregation):</strong> Grouping by all projected dimensions keeps each record at its own grain—child rows evaluate to 0, while the parent row evaluates to the parent&#39;s metric value.</li><li><strong>Outer </strong><strong>sum(...) over ([..] partition by ...) (Window Broadcast):</strong> Unlike a standard aggregation that collapses rows, the window function calculates across all rows ([..]) within each parent partition (partition by), keeping every row intact.</li><li><strong>Why This Is the Heart of the Solution:</strong> Summing across each partition (0 + 0 + ... + Metric) stamps every matching child row with its parent&#39;s metric—preserving record granularity without cogroup or circular recipe loops.</li></ul><pre>merge =  union Activity,Opportunity,Account;<br>final = group merge by (&#39;Account Id&#39;, &#39;Title&#39;, &#39;Type&#39;, &#39;Dummy id&#39;,&#39;Date&#39;,  &#39;Status&#39;);<br>final = foreach final generate &#39;Account Id&#39; as &#39;Account Id&#39;, &#39;Title&#39; as &#39;Title&#39;, &#39;Type&#39; as &#39;Type&#39;, &#39;Date&#39; as &#39;Date&#39;,sum(sum(&#39;Account_Health&#39;))   over ([..] partition by &#39;Account Id&#39;) as &#39;Account_Health&#39;, &#39;Dummy id&#39; as &#39;Dummy id&#39;,&#39;Status&#39; as &#39;Status&#39;;</pre><h4>Step 5 — Final Projection and Helper Row Filter</h4><p>Project only the display fields needed for the UI and filter out the synthetic parent helper rows so only the actual target records appear in the final output.</p><pre>final = filter final by &#39;Type&#39; != &quot;Account&quot;;<br>final = foreach final generate &#39;Title&#39;,&#39;Type&#39;,&#39;Date&#39;,&#39;Account_Health&#39;,&#39;Status&#39;;</pre><p>Final SAQL Query:</p><pre>Account = load &quot;AccountDataset&quot;;<br>Account = foreach Account generate &#39;Id&#39; as &#39;Account Id&#39;, &quot;-&quot; as &#39;Title&#39;, &quot;Account&quot; as &#39;Type&#39;, &quot;-&quot; as &#39;Date&#39;, &#39;Account_Health&#39; as &#39;Account_Health&#39;, &quot;-&quot; as &#39;Dummy id&#39;, &quot;-&quot; as &#39;Status&#39;;<br><br>Activity = load &quot;ActivitiesDataset&quot;;<br>Activity = filter Activity by (&#39;Status&#39; != &quot;Completed&quot; || &#39;Status&#39; is null);<br>Activity = filter Activity by date(&#39;ActivityDate_Year&#39;, &#39;ActivityDate_Month&#39;, &#39;ActivityDate_Day&#39;) in[&quot;current day&quot;..&quot;current day&quot;];<br>Activity = foreach Activity generate &#39;Account_Dynamic_Id&#39; as &#39;Account Id&#39;,&#39;Subject&#39; as &#39;Title&#39;,&#39;Activity_Type&#39; as &#39;Type&#39;,&quot;Today&quot; as &#39;Date&#39;,0 as &#39;Account_Health&#39;, &#39;Id&#39; as &#39;Dummy id&#39;,<br>(case when &#39;Activity_Type&#39; == &quot;Event&quot;<br>    then &#39;Meeting_Status&#39;<br>    when &#39;Activity_Type&#39; == &quot;Task&quot;<br>    then &#39;Status&#39;<br>end) as &#39;Status&#39;;<br><br>Opportunity = load &quot;OpportunityDataset&quot;;<br>Opportunity = filter Opportunity by date(&#39;CloseDate_Year&#39;, &#39;CloseDate_Month&#39;, &#39;CloseDate_Day&#39;) in [&quot;current day&quot;..&quot;current day&quot;];<br>Opportunity = filter Opportunity by &#39;StageName&#39; not in[&quot;Closed Won&quot;, &quot;Closed Lost&quot;];<br>Opportunity = foreach Opportunity generate &#39;AccountId&#39; as &#39;Account Id&#39;,&#39;Name&#39; as &#39;Title&#39;,&quot;Opportunity&quot; as &#39;Type&#39;,&quot;Today&quot; as &#39;Date&#39;, 0 as &#39;Account_Health&#39;, &#39;Id&#39; as &#39;Dummy id&#39;, &#39;StageName&#39; as <br>&#39;Status&#39;;<br><br>merge =  union Activity,Opportunity,Account;<br>final = group merge by (&#39;Account Id&#39;, &#39;Title&#39;, &#39;Type&#39;, &#39;Dummy id&#39;,&#39;Date&#39;,  &#39;Status&#39;);<br>final = foreach final generate &#39;Account Id&#39; as &#39;Account Id&#39;, &#39;Title&#39; as &#39;Title&#39;, &#39;Type&#39; as &#39;Type&#39;, &#39;Date&#39; as &#39;Date&#39;,sum(sum(&#39;Account_Health&#39;))     over ([..] partition by &#39;Account Id&#39;) as &#39;Account_Health&#39;, &#39;Dummy id&#39; as &#39;Dummy id&#39;,&#39;Status&#39; as &#39;Status&#39;;<br><br><br>final = filter final by &#39;Type&#39; != &quot;Account&quot;;<br>final = foreach final generate &#39;Title&#39;,&#39;Type&#39;,&#39;Date&#39;,&#39;Account_Health&#39;,&#39;Status&#39;;<br><br></pre><h3>Final Output:</h3><p>Account Health Score:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/266/1*pt2mHhQcaQi69jxwMInPDA.png" /><figcaption>Sample accounts Health Score</figcaption></figure><p>Given the Account Health scores above for Accounts, here is how their open tasks, events, and opportunities due today appear in the final table each stamped with its respective account’s health score at the row level:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*xReFuoSrDSkwmIRNgRAlFg.png" /><figcaption>Final Output</figcaption></figure><h3>Conclusion</h3><p>In CRM Analytics, it is easy to default to recipe joins whenever a dashboard needs a metric from another dataset — even when doing so introduces circular dependencies. The real takeaway is simple: <strong>let the use case and required data grain dictate your implementation.</strong></p><p>When you need row-level detail without reshaping your dataflows, handling the metric broadcast at query time via a partitioned window function keeps both your recipes and your dashboard tables clean.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6976f8073f4f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Pattern for Reducing Multiple Joins in CRM Analytics — Vol 5: Finding the Earliest Open…]]></title>
            <link>https://ramdosk92.medium.com/design-pattern-for-reducing-multiple-joins-in-crm-analytics-vol-5-finding-the-earliest-open-fe405484856c?source=rss-3d44b7a76dc9------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe405484856c</guid>
            <category><![CDATA[join-reduction]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[window-functions]]></category>
            <category><![CDATA[boundary-detection]]></category>
            <category><![CDATA[crm-analytics]]></category>
            <dc:creator><![CDATA[Ramdosk]]></dc:creator>
            <pubDate>Thu, 29 Oct 2026 22:54:45 GMT</pubDate>
            <atom:updated>2026-10-29T22:54:45.978Z</atom:updated>
            <content:encoded><![CDATA[<h3>Design Pattern for Reducing Multiple Joins in CRM Analytics — Vol 5: Finding the Earliest Open Opportunity Close Date per Account</h3><p><em>Use window calculations to identify the earliest projected Close Date among open opportunities while retaining the closed rows in the main Opportunity stream, without creating a separate open-opportunity stream and joining it back.</em></p><h3>Introduction</h3><p>Account buying-pace analysis can show whether the expected gap between purchases is longer or shorter than the account’s historical pattern. One input is the expected Close Date of the account’s earliest-dated open opportunity.</p><p>A straightforward recipe filters open opportunities into a separate stream, finds the earliest Close Date for each account, and joins that result back to the main Opportunity stream. This article shows how to identify and carry that date within the main stream. The projected buying gap and variance can then be calculated using this date, the latest Closed Won Close Date, and the account’s historical average buying interval.</p><h3>The Business Scenario</h3><p>A sales team wants to understand whether an account’s expected gap between purchases is increasing or decreasing compared with its historical buying pattern.</p><p>For each account, the analysis needs the earliest expected Close Date among its open opportunities. This date is compared with the most recent Closed Won Close Date to calculate the projected buying gap. That gap can then be compared with the average interval between the account’s previous Closed Won opportunities.</p><p>Here, “earliest” means the open opportunity with the earliest <strong>Close Date</strong>. It does not mean the opportunity with the earliest Created Date.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*GcpOtBSplfj1hFbrNIKSgA.png" /><figcaption>Sample Data</figcaption></figure><h3>The Tempting Design</h3><p>A common recipe layout is:</p><p><strong>Main stream:</strong> Opportunity records</p><p><strong>Open-opportunity stream:</strong></p><ul><li>Filter to open opportunities.</li><li>Find the earliest Close Date for each account.</li><li>Join that result back to the main Opportunity stream by Account ID.</li></ul><p>This is easy to understand, but adds a separate stream and a join to bring the selected date back.</p><h3>The Challenge: Calculating It in the Main Opportunity Stream Without an Additional Join</h3><p>An account can have multiple open opportunities, each with a different expected Close Date, alongside its closed opportunities. The recipe needs to identify the earliest expected Close Date among the open opportunities for each account and make that value available with the main Opportunity data.</p><p>The main-stream calculation needs to preserve the account’s opportunity rows while selecting the correct open opportunity from several candidates. The steps below use the Close Date ordering of those rows to identify and retrieve that date.</p><h3>Design Principle</h3><blockquote><em>Use the ordering of records within each account to identify the boundary row you need, then carry its value across the account’s rows. This can avoid creating a separate stream and joining its result back.</em></blockquote><h3>Step-by-Step Solution</h3><p>The earliest expected Close Date among an account’s open opportunities can be retrieved in two steps. First, create an intermediate field that retains the Close Date for the open opportunity at the boundary with the closed records and assigns a sentinel date to other rows. Then retrieve that date across the account’s Opportunity rows.</p><h3>Step 1: Create the Intermediate Close Date</h3><p>Each account can have multiple open and closed opportunities. The business needs the <strong>earliest expected Close Date among the open opportunities</strong>.</p><p>This boundary method assumes the open opportunities’ projected Close Dates are later than the historical Close Dates of closed opportunities. With that ordering, sorting an account’s opportunities from latest to earliest places the open opportunities first and the closed opportunities after them. The open row at the transition has the earliest expected Close Date among the open opportunities.</p><p>Create an intermediate field that keeps the Close Date on that row and assigns an old sentinel date to the other rows:</p><pre>case <br>    when current(IsClosed) = &#39;false&#39; AND (lead(IsClosed) = &#39;true&#39; OR (lead(IsClosed) = &#39;&#39; OR lead(IsClosed) is null))<br>    then current(CloseDate)<br>    <br>    else to_timestamp(&#39;1970-01-01&#39;, &#39;yyyy-MM-dd&#39;)<br>    <br>end<br><br></pre><p>Configure the Window functions to:</p><ul><li><strong>Partition by:</strong> AccountId</li><li><strong>Order by:</strong> CloseDate, descending</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*MyAZBls9LfXD0r8wIId8tA.png" /></figure><p>current(IsClosed) checks the current opportunity’s status, while lead(IsClosed) checks the next opportunity in the account’s ordered rows. When the current row is open and the next row is closed, the formula retains the current row’s Close Date. Either a Closed Won or Closed Lost opportunity can mark this boundary; its outcome does not affect which open opportunity’s expected date is selected.</p><p>The sentinel date lets the next step distinguish the selected Close Date from the other rows.</p><p>The recipe evaluates the condition across the ordered rows in each account partition. It does not need to split the rows into separate open and closed streams.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wAYHLPSKVG6KaqbeA0U32g.png" /><figcaption>Output</figcaption></figure><h3>Step 2: Retrieve the Open Opportunity Close Date Across the Account’s Rows</h3><p>Step 1 created an intermediate field containing the selected opportunity’s expected Close Date; the other rows contain the sentinel date. Create a second multiple-row formula to retrieve the selected date across the account’s Opportunity rows:</p><p>Create a second multiple-row formula:</p><pre>first_value(First_Open_Oppty_Close_Date_Intermidment)</pre><p>Configure the Window functions to:</p><ul><li><strong>Partition by:</strong> AccountId</li><li><strong>Order by:</strong> First_Open_Oppty_Close_Date_Intermidment, descending</li></ul><p>The actual expected Close Date sorts ahead of the sentinel date. first_value() returns that date across the account’s partition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*wnMZmR9uy7DH4Ll4N-LP9w.png" /><figcaption>First Open Oppty Close Date</figcaption></figure><p><strong>Output field:</strong> First_Open_Oppty_Close_Date</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rYsAgMRNofqfiwn-JxMkvw.png" /><figcaption>Output</figcaption></figure><p>This account-level value can now be used in the projected buying-gap calculation alongside the latest Closed Won Close Date.</p><h3>Step 3: Calculate the Projected Buying Gap</h3><p>Calculate the days between the earliest expected open Close Date and the account’s most recent Closed Won Close Date</p><pre>datediff(<br>  First_Open_Oppty_Close_Date,<br>  Latest_Closed_Won_Close_Date<br>)</pre><p>This gives the projected number of days from the most recent Closed Won Close Date to the earliest expected Close Date among the account’s open opportunities.</p><h3>Step 4: Compare the Projected Gap with Historical Buying Pace</h3><h3>Step 4: Calculate Buying-Pace Variance</h3><p>Use the computed projected buying gap and historical average buying gap to calculate the account’s buying-pace variance. Apply the calculation only when both values are valid, so a sentinel-based gap or missing historical baseline isn’t treated as a meaningful comparison.</p><p>A positive variance means the projected gap is longer than the account’s historical average; a negative variance means it is shorter. The recipe returns 0 when the calculation isn’t valid because the output field is numeric. If downstream users need to distinguish that fallback from a true 0% variance, provide a separate validity indicator.</p><h3>Fallback Logic</h3><p>The intermediate formula includes lead(IsClosed) = &#39;&#39; OR lead(IsClosed) is nullfor a row with no next value. For an account without a Closed Won history, the final buying-gap calculation must treat the gap and variance as unavailable rather than calculating against the sentinel date. Likewise, if an account has no qualifying open opportunity, return a blank or another agreed value.</p><h3>Final Output</h3><p>The resulting account-level values can be used to see whether the next expected purchase is projected to fall earlier or later than the account’s historical buying pattern.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UhkIRE1u-MBOPendVyyVKg.png" /><figcaption>Final Output</figcaption></figure><h3>Consideration</h3><p>The selected open Close Date and related account-level buying-gap values repeat across that account’s Opportunity rows. In downstream analysis, avoid summing these repeated values; use an appropriate non-additive aggregation or select one row per account.</p><h3>Alternative Approach: Composite Key and FIRST_VALUE()</h3><p>Another way to retrieve the earliest open Close Date is to create a composite key from AccountId and IsClosed. This creates separate partitions for each account’s open and closed opportunities.</p><pre>Concat(AccountId,&#39;-&#39;,IsClosed)</pre><p>In the first formula, partition by the composite key and order by CloseDate <strong>ascending</strong>. The first open opportunity in that partition has the earliest expected Close Date; assign the sentinel date to the closed partition:</p><pre>case<br>  when first_value(IsClosed) = &#39;false&#39;<br>  then first_value(CloseDate)<br>  else to_timestamp(&#39;1970-01-01&#39;, &#39;yyyy-MM-dd&#39;)<br>end</pre><p>Then use a second formula with AccountId as the partition and the intermediate date field as the descending sort order:</p><pre>first_value(Open_Opportunity_Earliest_CloseDate)</pre><p>The actual open Close Date sorts ahead of the sentinel, making it available across the account’s Opportunity rows without a separate stream and join. This approach also works, but it requires creating the composite key.</p><h3>Summary</h3><p>The recipe uses the ordered Opportunity rows to identify the open opportunity with the earliest expected Close Date, then carries that date across the account’s rows. This keeps the calculation in the main Opportunity stream and avoids creating a separate open-opportunity stream and joining it back.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe405484856c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Pattern for Reducing Multiple Joins in CRM Analytics — Vol 4: Finding the Most Recent Closed…]]></title>
            <link>https://ramdosk92.medium.com/design-pattern-for-reducing-multiple-joins-in-crm-analytics-vol-4-finding-the-most-recent-closed-7fc61bdfb8c6?source=rss-3d44b7a76dc9------2</link>
            <guid isPermaLink="false">https://medium.com/p/7fc61bdfb8c6</guid>
            <category><![CDATA[join-reduction-pattern]]></category>
            <category><![CDATA[window-functions]]></category>
            <category><![CDATA[data-recipe]]></category>
            <category><![CDATA[account-level-pipeline]]></category>
            <category><![CDATA[custom-sorting]]></category>
            <dc:creator><![CDATA[Ramdosk]]></dc:creator>
            <pubDate>Wed, 21 Oct 2026 15:03:45 GMT</pubDate>
            <atom:updated>2026-10-21T15:03:45.223Z</atom:updated>
            <content:encoded><![CDATA[<h3>Design Pattern for Reducing Multiple Joins in CRM Analytics — Vol 4: Finding the Most Recent Closed Opportunity per Account</h3><p><em>Derive the latest closed opportunity’s close date and stage for each account in the Opportunity stream, avoiding a separate closed-opportunity stream and an additional join.</em></p><h3>Introduction</h3><p>In the earlier articles in this series, we explored how reshaping data in a recipe can reduce joins introduced by a business requirement.</p><p>This article applies that approach to finding a specific opportunity within each account’s Opportunity records. A straightforward design calculates the result in a separate stream and joins it back to the main Opportunity stream. Here, the calculation stays in the Opportunity stream, avoiding that additional join.</p><h3>The Business Scenario</h3><p>A sales team wants to include a <strong>Most Recent Closed</strong> signal in its account-level pipeline analysis. For each account, the signal should show the Close Date of its latest closed opportunity, how many days ago it closed, and the opportunity’s stage.</p><p>The key requirement is to find the latest closed opportunity within each account’s opportunities. The result can then be used alongside other account-level pipeline information.</p><h3>The Challenge</h3><p>The recipe needs to:</p><ol><li>Consider opportunities separately within each account.</li><li>Sequence closed opportunities by Close Date, with the most recent first.</li><li>Retrieve the selected opportunity’s Close Date and stage.</li><li>Calculate how many days have passed since that Close Date.</li></ol><p>A separate stream can filter to closed opportunities and calculate these values. But because the result is created outside the main Opportunity stream, it must be joined back — typically using Account ID — to make the values available alongside opportunity data.</p><p><strong>Example opportunity records for one account.</strong> Open opportunities can have planned Close Dates later than closed opportunities. Sorting only by Close Date could therefore place an open opportunity ahead of the latest closed opportunity. The custom sort date in the next step accounts for this by placing open opportunities after closed ones.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*6S5iyIa1UQ3PLCtT4fhLGg.png" /><figcaption>Sample Records</figcaption></figure><h3>The Tempting Design</h3><p>A common recipe layout is:</p><p><strong>Main stream:</strong> Opportunity records</p><p><strong>Closed-opportunity stream:</strong></p><ul><li>Filter to closed opportunities.</li><li>Identify the most recent closed opportunity for each account.</li><li>Calculate the days since its Close Date.</li><li>Retrieve its stage.</li><li>Join the result to the main Opportunity stream by Account ID.</li></ul><p>This approach works, but it adds a stream and a join to return the selected date and stage. The alternative is to keep all opportunities in one stream and use transformations to rank closed opportunities first within each account.</p><h3>Design Principle</h3><blockquote><em>When the records needed to find a group-level value are already in the main stream, derive that value within the stream and carry it across the group’s rows. This can avoid a separate result stream and the join needed to bring it back.</em></blockquote><h3>Step-by-Step Solution</h3><h3>Step 1: Create a Custom Sort Close Date</h3><p>Create a date field that uses the opportunity’s actual CloseDate when it is closed and a fixed, sufficiently old date when it is open:</p><pre>case <br>    when IsClosed = &#39;true&#39;<br>    then CloseDate<br>    <br>    else to_timestamp(&#39;1970-01-01&#39;, &#39;yyyy-MM-dd&#39;)<br>    <br>end</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*meoN3YoUTUaSURAxaTmz6w.png" /><figcaption>Custom Sort Close Date</figcaption></figure><h3><strong>Why this matters</strong></h3><p>The business needs the most recent closed opportunity for each account, but the Opportunity stream contains both open and closed records. If the calculation sorts by the actual CloseDate, an open opportunity with a later planned Close Date could appear ahead of a closed opportunity. Assigning open opportunities an old date makes closed opportunities sort first, while their actual Close Dates determine which one is most recent. This lets the recipe identify the right opportunity while retaining both types of records in the stream.</p><h4>Step 2: Order Opportunities Within Each Account</h4><p>With the custom field from Step 1, open opportunities sort to the end of each account’s group, while closed opportunities come first. Configure the window calculation to partition the rows by account and order them by the custom sort date in descending order:</p><ul><li><strong>Partition by:</strong> AccountId</li><li><strong>Order by:</strong> Custom_Sort_Close_Date, descending</li></ul><p>Each account’s most recent closed opportunity is now first in its ordered group. Use first_value() to retrieve the relevant value from that opportunity.</p><p>The business wants the close date displayed as text like <strong>“250d ago.”</strong> First, datediff() calculates the number of days since the selected Close Date. Then string() converts that number to text, and concat() appends d ago:</p><pre>concat(<br>  string(datediff(current_date(), first_value(Custom_Sort_Close_Date))),<br>  &#39;d ago&#39;<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*OIBSqbYqSDQV1EYrwjtoUg.png" /><figcaption>Latest Closed Oppty Close Date</figcaption></figure><p>If you want to display the Close Date itself instead, use first_value(Custom_Sort_Close_Date) and format the returned date for display.</p><p><strong>Accounts with no closed opportunities:</strong> If an account has no closed opportunities, the first row is an open opportunity, so this formula uses the old date assigned in Step 1 and produces a large day count. That is intentional: returning 0d ago would suggest an opportunity closed today. The unusually large value acts as an outlier, indicating that the account has no closed opportunities.</p><h4>Step 3: Retrieve the Most Recent Closed Opportunity’s Stage</h4><p>Use first_value(StageName) with the same account partition and custom-date ordering to retrieve the stage from the first opportunity in each account’s ordered group:</p><pre>first_value(StageName)</pre><h4>Fallback Logic: Handle Accounts with No Closed Opportunities</h4><p>The custom sort date puts closed opportunities first when an account has at least one. If an account has no closed opportunities, its first row is still an open opportunity. Returning first_value(StageName) alone would show that open opportunity’s stage as the most recent closed stage.</p><p>Check whether the first opportunity is closed before returning its stage:</p><pre>case <br>    when first_value(IsClosed) = &#39;false&#39;<br>    then &#39;-&#39;<br>    else first_value(StageName)<br>    <br>end</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*ZoL4icgdmRaP2AQMf-tEtA.png" /><figcaption>latest Closed Oppty Stage</figcaption></figure><p>This returns - when the account has no closed opportunities and otherwise returns the actual stage of its most recent closed opportunity.</p><p>If the business wants labels such as “Won” or “Lost” instead of the actual stage names, handle that naming in XMD. This keeps the recipe from hardcoding display labels into the stage comparison.</p><h4><strong>Step 4: Use the Values Downstream</strong></h4><p>The selected date, stage, and age are now available on the opportunity rows in each account’s partition. Downstream steps can use these values without joining a separate latest-closed-opportunity result stream back to the Opportunity stream.</p><p>These account-level values repeat across the account’s opportunity rows. If a downstream view needs one row per account, select or aggregate the data accordingly. Do not sum repeated dates or day counts in downstream analysis.</p><h3>Final Output</h3><p><em>The account-level view shows each account’s most recent closed opportunity age and stage. Accounts without a closed opportunity show “–” for the stage and a large day count as the agreed indicator.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*ooQgQH2-7b_3jc80MD7dmA.png" /><figcaption>Final Output</figcaption></figure><h4><strong>What This Design Changes</strong></h4><p>The separate-stream approach calculates the latest closed opportunity per account on a closed-only path, then joins that result back to the Opportunity stream. This design keeps the calculation in the Opportunity stream and avoids that additional join.</p><p>The established benefit is a simpler recipe shape with one fewer join for this result.</p><h3>Summary</h3><p>This pattern uses a custom sort date to make the latest closed opportunity identifiable within each account’s Opportunity rows. Window calculations then make its date and stage available across those rows, avoiding a separate closed-opportunity stream and the join needed to bring its results back.</p><p>The broader recipe design lesson is to shape the records in the existing stream so the required result can be calculated there. That can reduce joins while keeping the output available for downstream analysis.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7fc61bdfb8c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Pattern for Reducing Multiple Joins in CRM Analytics — Vol 3: Using Window Functions to…]]></title>
            <link>https://ramdosk92.medium.com/design-pattern-for-reducing-multiple-joins-in-crm-analytics-vol-3-using-window-functions-to-7f42b6df5da5?source=rss-3d44b7a76dc9------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f42b6df5da5</guid>
            <category><![CDATA[aggregation]]></category>
            <category><![CDATA[join-reduction]]></category>
            <category><![CDATA[pivoting]]></category>
            <category><![CDATA[window-fucntion]]></category>
            <category><![CDATA[custom-key]]></category>
            <dc:creator><![CDATA[Ramdosk]]></dc:creator>
            <pubDate>Tue, 13 Oct 2026 11:04:49 GMT</pubDate>
            <atom:updated>2026-10-13T11:04:49.420Z</atom:updated>
            <content:encoded><![CDATA[<h3>Design Pattern for Reducing Multiple Joins in CRM Analytics — Vol 3: Using Window Functions to Bring Closed Won Activity Averages into Opportunity</h3><h3>A Practical Approach Using Opportunity Activity Data</h3><h3>Introduction</h3><p>In CRM Analytics Data Recipes, a solution can meet the business requirement and still become harder to maintain as more data streams and joins are added. This often happens when related metrics are calculated in separate branches and each branch is joined back to the main dataset.</p><p>This article looks at that problem in an Opportunity associated activities transformations. The Opportunity dataset needs two results: stage wise activity counts for individual opportunities, and average stage wise activity counts across Closed Won opportunities for downstream analysis. A straightforward design calculates those results in separate streams, requiring two joins back to Opportunity.</p><p>The recipe pattern described here combines both results in one activity stream and brings them into Opportunity through one join instead of two. This reduces the number of joins in the recipe</p><h3>The Business Scenario</h3><p>The business needs to understand activity across the stages of the opportunity lifecycle.</p><p>For each opportunity, the recipe attributes activities to the stage that was active when each activity occurred and calculates stage wise activity counts. Separately, the business needs the average activity count at each stage across Closed Won opportunities for downstream analysis.</p><p>The intended outputs are therefore:</p><ul><li>Stage wise activity counts at the individual opportunity level.</li><li>Average stage wise activity counts across Closed Won opportunities.</li></ul><p>These outputs have different levels of detail, but both need to be available alongside Opportunity data.</p><h3>The Challenge</h3><p>Activities and opportunity stage history are stored as separate records. An activity has a date and a link to an opportunity; stage history records when an opportunity changed stages. The recipe first has to determine which stage was active on each activity date, then aggregate those activities by opportunity.</p><p>There is also a grain difference between the required outputs:</p><ul><li>Activity counts are calculated for each opportunity.</li><li>Closed Won averages are calculated across the Closed Won population.</li></ul><p>That difference can lead to separate recipe branches. The per-opportunity activity counts retain an opportunity key, while a Closed Won average calculated by collapsing the population to one row no longer has an individual opportunity key to match against.</p><h3>The Tempting (but Inefficient) Design</h3><p>A straightforward recipe design splits the work into two result streams.</p><p><strong>Open opportunity activity stream</strong></p><ol><li>Attribute activities to opportunity stages.</li><li>Aggregate stage activity counts by opportunity.</li><li>Keep the Open opportunity results.</li><li>Join those results to Opportunity using the opportunity key.</li></ol><p><strong>Closed Won averages stream</strong></p><ol><li>Attribute activities to opportunity stages.</li><li>Aggregate stage activity counts by opportunity.</li><li>Keep the Closed Won opportunities.</li><li>Aggregate again to get the total activity count at each stage and the number of Closed Won opportunities.</li><li>Calculate the average for each stage.</li><li>Join the average result to Opportunity.</li></ol><p>The second aggregation collapses the Closed Won stream to population-level values. Since that result no longer has an opportunity key, a custom key is needed to attach it to the Opportunity stream. In this design, the Open activity results and Closed Won averages each require their own join back to Opportunity.</p><p>While this approach can produce the required outputs, it creates another branch and join to maintain. If the recipe needs more population-level metrics later, the same pattern can add further aggregation and join steps.</p><h3>Design Principle</h3><blockquote><em>When per-opportunity metrics and population-level metrics come from the same activity stream, calculate them together while retaining the opportunity grain, then join the combined result to Opportunity once.</em></blockquote><h3>Step-by-Step Solution</h3><p>The goal is to calculate Open opportunity stage activity counts and Closed Won average stage activity counts in one activity stream, then bring the results into Opportunity with one join.</p><h3>Step 1: Attribute each activity to an opportunity stage</h3><p>An activity has a date, and opportunity history records when the opportunity changed stages. Bring the relevant stage dates into the activity stream, then compare each activity date with those boundaries to identify the stage that was active when the activity occurred.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*7_vk2q_mmGk3NHdRIsYcfA.png" /><figcaption>Opportunity Wise Stage Change Date</figcaption></figure><blockquote>S1 Date -&gt; Stage 1 Date</blockquote><p>Create a numeric flag for each stage. For example, an activity during S1 receives 1 in the S1 flag and 0 in the other stage flags.</p><pre>case <br>    when &quot;OpportunityActivity.Opportunity_Status&quot; = &#39;Closed Won&#39;<br>    then <br>        case <br>            when Status = &#39;Completed&#39;<br>            then <br>                case <br>                    when ActivityDate &gt;= &quot;StageChangeDate.S1_Date&quot; AND ActivityDate &lt; coalesce(&quot;StageChangeDate.S2_Date&quot;,to_timestamp(&#39;9999-12-31&#39;,&#39;yyyy-MM-dd&#39;))<br>                    then 1<br><br>                    else 0<br><br>                end<br>            <br>            else 0<br>            <br>        end<br>    <br>    else <br>        case <br>            when ActivityDate &gt;= &quot;StageChangeDate.S1_Date&quot; AND ActivityDate &lt; coalesce(&quot;StageChangeDate.S2_Date&quot;,to_timestamp(&#39;9999-12-31&#39;,&#39;yyyy-MM-dd&#39;))<br>            then 1<br><br>            else 0<br><br>        end<br>    <br>end<br><br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*bDZljpNr1jBcewL8VDn8tA.png" /></figure><p>Apply the same logic to the other stages and to any Unassigned case required by the business rules. These flags let the recipe count activities by stage in the next step.</p><h3>Step 2: Aggregate stage activity counts by opportunity category</h3><p>The business needs stage wise activity counts for Open opportunities and Closed Won activity counts that will be used to calculate stage averages.</p><p>Create an <strong>Opportunity Category</strong> field that classifies each opportunity as Open or Closed Won.</p><pre>case <br>    when IsClosed = &#39;true&#39;<br>    then <br>            case <br>                when IsWon = &#39;true&#39;<br>                then &#39;Closed Won&#39;<br>                <br>                else &#39;Closed Lost&#39;<br>                <br>            end<br>    <br>    else &#39;Open&#39;<br>    <br>end</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*mdejhk3vj0HLZA-AQ4Wn-w.png" /><figcaption>Opportunity Status</figcaption></figure><p>Then group the stage flags by opportunity ID, sum each flag, and pivot on Opportunity Status.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/263/1*GzY8htNIuDnTfg_-NGTPxg.png" /><figcaption>Aggregation Node</figcaption></figure><p>The output has one row per opportunity, with the stage activity counts split into Open and Closed Won fields. An Open opportunity’s counts appear in the Open fields; a Closed Won opportunity’s counts appear in the Closed Won fields.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*8fhNzAQG7pXstp8Eo5Ky9A.png" /><figcaption>Pivoted Columns</figcaption></figure><p>This keeps both populations in one aggregate result. The Open counts remain available per opportunity, while the Closed Won counts are ready for the population average calculation.</p><h3>Step 3: Recreate Opportunity Category for the window calculations</h3><p>The pivot turns the original category values into separate Open and Closed Won columns. The window calculations need a single category value on each opportunity row so they can partition rows into Open and Closed Won groups.</p><p>First, calculate total activity fields from the split stage counts. For Closed Won, sum the S1, S2, S3, S4, and Unassigned columns:</p><pre>coalesce(SUM_S1_Opportunity_Stage_During_Activity_ClosedWon, 0)<br>+ coalesce(SUM_S2_Opportunity_Stage_During_Activity_ClosedWon, 0)<br>+ coalesce(SUM_S3_Opportunity_Stage_During_Activity_ClosedWon, 0)<br>+ coalesce(SUM_S4_Opportunity_Stage_During_Activity_ClosedWon, 0)<br>+ coalesce(SUM_Unassigned_Opportunity_Stage_During_Activity_ClosedWon, 0)</pre><p>Create Total_Open_Oppty_Activities the same way, using the corresponding Open columns. The coalesce calls treat missing pivot values as zero.</p><p>Then create a category field from these totals. For example, classify a row as Closed Won when it has Closed Won activity counts; otherwise, classify it as Open when it has Open activity counts.</p><pre>case <br>    when Total_Closed_Won_Oppty_Activities &gt; 0<br>    then &#39;Closed Won&#39;<br>    when Total_Open_Oppty_Activities &gt; 0<br>    then &#39;Open&#39;<br>    <br>    else &#39;&#39;<br>    <br>end</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*z-avnud_I_nAEotfhqD_Rw.png" /><figcaption>Oppty Category Column</figcaption></figure><p>This post-aggregate category is distinct from the category field used to pivot the aggregate. The window calculations in the next steps use the new field to partition opportunity rows into Closed Won and Open groups</p><h3>Step 4: Calculate each Closed Won stage total with a window SUM</h3><p>For each stage, calculate the total Closed Won activity count across the Closed Won opportunity rows.</p><p>Conceptually, for S1:</p><p>Configure the window to partition by the post-aggregate Opportunity Category and order by that same category field:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*nANwGTYIObZeOeEGIsUZRA.png" /><figcaption>Total no of S1 stage Activity</figcaption></figure><p>Within each partition, all rows have the same category value and are peers in the ordering. With Spark SQL’s default ordered window frame, the SUM includes the full peer group. The resulting Closed Won stage total is therefore available on each Closed Won row.</p><p>Repeat the calculation for S2, S3, and S4. Use the raw activity counts so these totals represent activities, not scores.</p><h3>Step 5: Add a unique opportunity count to the aggregate</h3><p>The aggregate groups records by WhatId, so each output row represents one opportunity. In that same aggregate, add Unique(WhatId) as a measure. It returns 1 for each opportunity group, giving every row a value that can be summed to count opportunities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/1*thapIpFmPt0tWsKOuX_MFw.png" /><figcaption>Aggregation Node</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SCu3BWehUV7N9-GdGR2PEg.png" /></figure><h3>Step 6: Count Closed Won opportunities with a window SUM</h3><p>Use a window SUM on the unique opportunity count, partitioned and ordered by the post-aggregate Opportunity Category:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*r_KvA6iO8wDflSe0Mm1XRA.png" /><figcaption>Total No of Closed Won Oppty</figcaption></figure><p>Because each Closed Won row contributes 1, the sum gives the number of Closed Won opportunities in that category. Use this value as the denominator when calculating the Closed Won average for each stage.</p><blockquote>This counts Closed Won opportunities present in the activity aggregate. If the average must include Closed Won opportunities with no qualifying activities, calculate the Closed Won opportunity count from the Opportunity data stream instead: create a numeric flag for Closed Won opportunities, then use a window SUM to get the total count.</blockquote><h3>Step 7: Calculate the Closed Won average for each stage</h3><p>Divide each Closed Won stage total from Step 4 by the Closed Won opportunity count from Step 6.</p><pre>coalesce((Total_Number_of_S1_Stage_Activity_Closed_Won / Total_Closed_Won_Oppty),0)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*2tpFML5RttHm2IVQ1UHLmg.png" /><figcaption>Stage 1 Avg Closed Won oppty Activity</figcaption></figure><p>Repeat for S2, S3, and S4. These calculations produce average activity counts per stage across the Closed Won population.</p><h3>Step 8: Keep only the fields needed downstream</h3><p>Before joining to Opportunity, remove intermediate fields that downstream users do not need, such as temporary flags, calculation-only columns. Retain the opportunity key, required per-opportunity activity counts, and Closed Won stage averages.</p><h3>Step 9: Join the combined result to Opportunity once</h3><p>Join the prepared activity result to Opportunity using the opportunity ID:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/437/1*LPtZZq-GsEWH25VLE0fYVw.png" /><figcaption>Oppty Activity onto Opportunity Join</figcaption></figure><p>The single join brings the activity metrics and Closed Won stage averages into the Opportunity data stream.</p><h3>Optional note: Excluding Closed Won opportunity-level activity counts</h3><p>If the business needs stage wise activity counts only for Open opportunities, filter the activity result to Open opportunities after calculating the Closed Won averages. This removes the Closed Won per-opportunity detail rows before the join.</p><h3>Summary</h3><p>The key design principle is to calculate population-level metrics on the entity-level stream whenever possible. This keeps the result joinable by its real key and avoids a separate aggregate stream and an additional join.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f42b6df5da5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Build YoY Analysis in Tableau Next — From Semantic Modeling to Agentforce Insights]]></title>
            <link>https://ramdosk92.medium.com/how-to-build-yoy-analysis-in-tableau-next-from-semantic-modeling-to-agentforce-insights-eab9ad833f7b?source=rss-3d44b7a76dc9------2</link>
            <guid isPermaLink="false">https://medium.com/p/eab9ad833f7b</guid>
            <category><![CDATA[agentforce]]></category>
            <category><![CDATA[yoy]]></category>
            <category><![CDATA[semantics]]></category>
            <category><![CDATA[pyoy]]></category>
            <category><![CDATA[year-over-year]]></category>
            <dc:creator><![CDATA[Ramdosk]]></dc:creator>
            <pubDate>Thu, 01 Oct 2026 11:10:52 GMT</pubDate>
            <atom:updated>2026-10-01T11:10:52.866Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Year-over-year (YoY) analysis is one of the most common requirements in business analytics: compare revenue with the previous year and understand how growth is changing.</p><p>In traditional BI tools, this type of analysis can often be handled using table calculations that compare values within a visualization. With Tableau Next, the approach is different when the business logic needs to be defined and reused through the semantic model.</p><p>In this blog, we’ll build a YoY revenue analysis in Tableau Next by creating reusable revenue and growth measures and then use them with Agentforce to analyze the results across products and accounts.</p><h3>Business Use Case</h3><p>Imagine a company preparing for its annual planning cycle.</p><p>Leadership wants to understand:</p><ul><li>What is the current-year revenue?</li><li>How does it compare with the previous year?</li><li>How did the previous year’s growth compare with the year before?</li><li>Which products are driving the growth or decline?</li><li>Which accounts are contributing to the change?</li></ul><p>For example, knowing that revenue is down <strong>5% YoY</strong> doesn’t tell the complete story. The decline could be concentrated in a particular product or a small number of accounts.</p><p>The goal is to move from:</p><p><strong>“Revenue is down.”</strong></p><p>to:</p><p><strong>“Where is the decline happening, and how has the growth trend changed?”</strong></p><h3>Approach</h3><p>The approach is to first establish a reliable semantic foundation and then define reusable revenue and growth measures on top of it.</p><p>The overall process is:</p><ol><li>Bring the required data objects into the semantic model.</li><li>Establish relationships based on the underlying business structure and grain.</li><li>Define revenue at the appropriate transactional grain.</li><li>Create reusable current-year and historical revenue measures.</li><li>Derive YoY growth measures from those revenue measures.</li><li>Use the measures across different dimensions.</li><li>Use Agentforce to analyze the results conversationally.</li></ol><p>Before implementing the calculations, however, there are three important semantic modeling decisions to understand.</p><h3>Key Semantic Modeling Decisions</h3><h3>1. Why Use a Many-to-One Relationship?</h3><p>For this use case, the relationship between Order Item and Order Header is:</p><p><strong>Order Item — Many → One — Order Header</strong></p><p>A single Order Header can contain multiple Order Items, while each Order Item belongs to one Order Header.</p><p>This cardinality reflects the natural transactional structure of the data.</p><p>It is also an important dimensional-modeling principle to keep in mind: relationship cardinality should reflect the <strong>grain and business meaning of the underlying data</strong>, rather than simply connecting objects because they share a key.</p><p>Here, Order Item represents the lower-level transaction, while Order Header provides the order-level context.</p><p>Establishing the appropriate cardinality helps preserve the intended grain of the data and reduces the risk of incorrect aggregation or duplicated values when measures are calculated across related objects.</p><h3>2. Why Calculate Revenue at the Order Item Level?</h3><p>The second important decision is the grain at which revenue should be calculated.</p><p>Revenue exists at the <strong>Order Item</strong> level, while attributes such as Order Start Date and Order Status come from the <strong>Order Header</strong>.</p><p>Therefore, the revenue calculation is intentionally performed at the Order Item grain.</p><blockquote>If revenue were taken from the Order Header’s Total Amount, a breakdown by product would repeat each order’s full total for every product on it</blockquote><p>This follows a core dimensional-modeling principle: define and preserve the appropriate grain of the measurement before building analytical logic.</p><p>Calculating revenue at the Order Item level also provides greater analytical flexibility.</p><p>Once the revenue measure is defined at this transactional grain, the same measure can be analyzed across different dimensions without creating separate revenue calculations for every perspective:</p><p><strong>Product → Account → Region → Sales Rep → and other dimensions</strong></p><p>For example, the same Current Year Revenue measure can be used to analyze revenue by Product and then by Account without changing the underlying business logic.</p><p>This becomes particularly important for our Agentforce use case. Because the measures are defined at the appropriate grain, Agentforce can use the same semantic measures to answer different analytical questions across dimensions.</p><p><strong>Key takeaway:</strong> Define a measure at the appropriate business grain once, then allow the dimensions to drive how that measure is analyzed.</p><h3>3. Why Create and Clearly Describe Semantic Measures?</h3><p>This is where it is important to distinguish between the <strong>calculation</strong> and the <strong>semantic measure</strong>.</p><p>The <strong>calculation</strong> defines <em>how the value is computed</em>.</p><p>The <strong>semantic measure</strong> defines <em>what that value means to the business</em>.</p><p>For example, the calculation for Current Year Revenue may be:</p><p>That expression tells Tableau Next how to calculate the value. But for conversational analytics, the measure also needs a clear business definition.</p><p>A semantic description could be:</p><p><strong>“Current calendar year revenue (Jan 1 to today): sum of order product Total Price, Activated orders, by order start date. Break down by order Product Name, account or rep. Not by case fields. Use instead of Order Total Amount.”</strong></p><p>The description provides additional semantic context, such as:</p><ul><li>What the measure represents</li><li>Which date determines the time period</li><li>Which business conditions apply</li><li>What underlying value is being aggregated</li><li>Which dimensions can be used to analyze it</li></ul><p>This distinction becomes especially important when the measure is used by Agentforce.</p><p>When a user asks a natural-language question such as:</p><p>“What is our current-year revenue by product?”</p><p>Agentforce needs more than a measure name. The semantic definition helps provide the business context needed to identify and use the appropriate measure.</p><p>The same principle applies to the YoY growth measures. The calculation determines the mathematical result, while the semantic definition explains what the result represents.</p><p><strong>Key takeaway:</strong> The calculation defines <strong>how to calculate the number</strong>; the semantic definition explains <strong>what the number means and how it should be used</strong>.</p><p>With these three modeling decisions established, we can now build the actual measures.</p><h3>Step-by-Step Solution</h3><h3>Step 1: Establish the Data Model and Relationship</h3><p>Bring the required data into the semantic model.</p><p>Establish the relationship as:</p><p><strong>Many → One</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*Os8JU1O5Xnw1vE-4ZWIJeA.png" /><figcaption>Semantic Model</figcaption></figure><h3>Step 2: Create Current Year Revenue</h3><p>Revenue is calculated at the Order Item level while using Order Header attributes for the business conditions.</p><pre>IF YEAR([Sales Order].[Order Start Date]) = YEAR(TODAY()) AND [Sales Order].[Sales Order Status] = &quot;Activated&quot;  THEN [Sales Order Product].[Total Price Amount]<br>ELSE 0<br>END</pre><p><strong>Field description:</strong></p><blockquote>Current calendar year revenue (Jan 1 to today): sum of order product Total Price, Activated orders, by order start date. Break down by order Product Name, account or rep. Not by case fields. Use instead of Order Total Amount.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/1*NRbZiY3584qGuRq-bntCRQ.png" /><figcaption>Current Year Revenue</figcaption></figure><h3>Step 3: Create Previous Year Revenue</h3><p>Apply the same logic to the previous calendar year, so the current year has a baseline to compare against.</p><pre>IF YEAR([Sales Order].[Order Start Date]) = YEAR(TODAY()) - 1 AND [Sales Order].[Sales Order Status] = &quot;Activated&quot;  THEN [Sales Order Product].[Total Price Amount]<br>ELSE 0<br>END</pre><p><strong>Field description:</strong></p><blockquote>Previous full calendar year revenue: sum of order product Total Price, Activated orders, by order start date. Break down by order Product Name, account or rep. Not by case fields. Baseline for YoY Revenue Growth %.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*WHWfyUWeRL4r7G29OD2HLw.png" /><figcaption>Previous Year Revenue</figcaption></figure><h3>Step 4: Create Previous-to-Previous Year Revenue</h3><p>Apply the same logic to the year before last, so you can see how last year’s growth compares with the year before.</p><pre>IF YEAR([Sales Order].[Order Start Date]) = YEAR(TODAY()) - 2 AND [Sales Order].[Sales Order Status] = &quot;Activated&quot;  THEN [Sales Order Product].[Total Price Amount]<br>ELSE 0<br>END</pre><p><strong>Field description:</strong></p><blockquote>Revenue for the calendar year two years ago: sum of order product Total Price, Activated orders, by order start date. Break down by order Product Name, account or rep. Not by case fields. Baseline for Prior Year Growth %.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*9J62j2ZKRNPIFglz7aodKg.png" /><figcaption>Previous to previous Year</figcaption></figure><h3>Step 5: Calculate Current YoY Growth %</h3><p>Now that the three revenue measures are available, calculate the current YoY growth:</p><p>In Tableau Next, wrap the revenue measures in SUM() so that the YoY ratio is calculated using the aggregated totals. Set the aggregation to <strong>UserAgg</strong> and format the resulting field as a percentage.</p><pre>(SUM([Current Year Revenue]) - SUM([Previous Year Revenue]))/SUM([Previous Year Revenue])</pre><p><strong>Field description:</strong></p><blockquote>(Current Year Revenue — Previous Year Revenue) / Previous Year Revenue. Valid by order Product Name, account or rep; not by case fields. Current year is year to date, so growth vs a full prior year may be understated.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*JfOYRLhiddGYCzzYRt_5jA.png" /><figcaption>YOY Revenue Growth</figcaption></figure><p><strong>Important:</strong> The Current Year Revenue measure represents the current calendar year up to today, while Previous Year Revenue represents the full previous calendar year. Therefore, this is not a like-for-like YoY comparison.</p><p>For a true like-for-like comparison, apply the same period logic to both years — for example, comparing revenue from January 1 through today against the same period in the previous year.</p><h3>Step 6: Calculate Previous YoY Growth %</h3><p>Similarly, calculate the previous year’s YoY growth:</p><p>This allows us to see not only the current revenue change, but also how the growth trend has changed.</p><pre>(SUM([Previous Year Revenue]) - SUM([Previous to Previous year Revenue])) / SUM([Previous to Previous year Revenue])</pre><p><strong>Field description:</strong></p><blockquote>(Previous Year Revenue — Previous to Previous Year Revenue) / Previous to Previous Year Revenue. Both full calendar years. Valid by order Product Name, account or rep; not by case fields.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/1*Qzhg4Ce3o3OdPZI8S0bllA.png" /><figcaption>Previous YOY Growth</figcaption></figure><h3>Step 7 (Optional) : Add Service Signals</h3><p>To look for possible causes behind a revenue decline, add <strong>Case</strong> and <strong>Asset</strong> to the semantic model:</p><ul><li>Relate <strong>Case → Account</strong> and <strong>Case → Asset</strong>, both <strong>Many to One</strong>.</li><li>Use the asset’s product as <strong>Case Product</strong>, so each case is linked to the product it was raised against.</li><li>Create case measures such as <strong>Current Year Case Count</strong> and <strong>Previous Year Case Count</strong>, based on the case Created Date.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*OYj1rSkHVORv-bO4eByqvQ.png" /><figcaption>Case related Calculated fields</figcaption></figure><p>Keep Case separate from the order objects. Revenue and cases then stay accurate, and the agent can analyse both by account.</p><h3>See It in Action</h3><p>With the semantic measures in place, let’s see how they support a natural line of questioning in Agentforce: from the overall trend, down to the accounts behind it, and then to possible causes.</p><h4>1. Product-Level Analysis</h4><p>We start by looking at how each product is performing compared with last year:</p><blockquote><em>“Show YoY revenue growth by product, only for products with revenue in either year, sorted by current year revenue.”</em></blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplayer.vimeo.com%2Fvideo%2F1231965242%3Fapp_id%3D122963&amp;dntp=1&amp;display_name=Vimeo&amp;url=https%3A%2F%2Fvimeo.com%2F1231965242%3Fshare%3Dcopy%26fl%3Dsv%26fe%3Dci&amp;image=https%3A%2F%2Fi.vimeocdn.com%2Fvideo%2F2207255408-bcde476afc4fcdcc27f7984ed697491cfa94883d0adddbb98b25c00a58b269d7-d_1280%3Fregion%3Dus&amp;type=text%2Fhtml&amp;schema=vimeo" width="1280" height="720" frameborder="0" scrolling="no"><a href="https://medium.com/media/de1242650e30e6bcb0b19e3f9eb5b172/href">https://medium.com/media/de1242650e30e6bcb0b19e3f9eb5b172/href</a></iframe><p>Starter Kit (−7.97%) and Power Inverter (−18.5%) are driving the decline, while Large Turbine is still growing. Because revenue is calculated at the Order Item level, the product totals add up exactly to the company total.</p><h4>2. Account-Level Analysis</h4><p>Next, we find out which customers are behind the decline in these two products:</p><blockquote><em>“For Starter Kit and Power Inverter combined into one total per account (don’t break down by product), show the accounts with the largest revenue decline between the previous year and the current year. Include each account’s current year revenue, previous year revenue, revenue change ($) and YoY growth %. Sort by revenue change, largest decline first, and show the top 10.”</em></blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplayer.vimeo.com%2Fvideo%2F1231966598%3Fapp_id%3D122963&amp;dntp=1&amp;display_name=Vimeo&amp;url=https%3A%2F%2Fvimeo.com%2F1231966598%3Ffl%3Dpl%26fe%3Dsh&amp;image=https%3A%2F%2Fi.vimeocdn.com%2Fvideo%2F2207257202-2339f7ae6149ebffcbde04aaad1b8d6b4265f5d021838b97afe166238ad8d65a-d_1280%3Fregion%3Dus&amp;type=text%2Fhtml&amp;schema=vimeo" width="1280" height="720" frameborder="0" scrolling="no"><a href="https://medium.com/media/8130a168b5752c823253fd0d5bf38e75/href">https://medium.com/media/8130a168b5752c823253fd0d5bf38e75/href</a></iframe><p>Ten established accounts account for about $1.5M of lost revenue, and several have placed no orders so far this year. The same revenue measures answer the question at account level, with no new calculations.</p><h4>3. Looking for the Cause</h4><p>Finally, we check whether service issues could help explain the decline at these accounts:</p><blockquote><em>“For these accounts, using the exact account names from the previous result, show the number of open and closed cases in the current year, broken down by case priority and type. Highlight accounts with rising case counts compared with last year.”</em></blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplayer.vimeo.com%2Fvideo%2F1231968550%3Fapp_id%3D122963&amp;dntp=1&amp;display_name=Vimeo&amp;url=https%3A%2F%2Fvimeo.com%2F1231968550&amp;image=https%3A%2F%2Fi.vimeocdn.com%2Fvideo%2F2207259790-0b1b6296c6284f8930e72223bfd1147d03317387c76fee85e0c03af00ea90cde-d_1280%3Fregion%3Dus&amp;type=text%2Fhtml&amp;schema=vimeo" width="1280" height="720" frameborder="0" scrolling="no"><a href="https://medium.com/media/736471ef130cf9c4a65796cc4ca7de51/href">https://medium.com/media/736471ef130cf9c4a65796cc4ca7de51/href</a></iframe><p>These accounts have logged as many support cases in nine months as in all of last year, mostly High and Critical Technical Issues. That doesn’t prove the cause, but it tells the account and product teams exactly where to look first.</p><h3>Things to Consider</h3><h4>Field descriptions aren’t a one-time task</h4><p>Agentforce chooses fields, filters and groupings largely from their names and descriptions. A description that looks clear to a person can still lead the agent down the wrong path. Treat descriptions as something you refine by testing:</p><ol><li>Write a first version: what the field is, how it’s calculated, its time basis and filters, and how it should be used.</li><li>Ask Agentforce the questions your business users will actually ask.</li><li>Check the answer’s <strong>Data Source</strong>: Fields Used, Filters Applied and the grouping.</li><li>If the agent chose the wrong field or grouping, adjust the description and test again.</li></ol><p>In this build, the descriptions changed several times based on the agent’s answers. For example, we added explicit guidance on which product field to use for revenue and which to use for cases.</p><h4>Tell the agent what a field shouldn’t be used for</h4><p>Saying what a measure <em>can’t</em> do is often as useful as saying what it can. Adding lines such as “not by case fields” to the revenue measures stopped the agent from breaking revenue down by case priority or type, which otherwise inflates the totals.</p><h4>Make similar fields clearly different</h4><p>When two fields look alike, such as Product Name from order lines and Case Product from the linked asset, give each a distinct label. Then make each description point to the other: <em>use this one for revenue, use that one for cases.</em></p><h4>Keep descriptions short and focused</h4><p>Description fields have a character limit (around 255 characters in our testing). Put the essentials first: the definition, the filter, how it can be broken down, and when not to use it.</p><h4>Use the readiness and testing tools</h4><p>Tableau Next’s <strong>Analytics Agent Readiness</strong> pane checks your field names, descriptions and relationships. <strong>Q&amp;A Calibration (Beta)</strong> lets you test questions in Concierge and verify the answers. Review any AI-generated descriptions before saving, and hide fields that users shouldn’t analyse.</p><h4>Check the agent’s answers against the source data</h4><p>Before rolling out to business users, compare the agent’s answers with the source data or a trusted report. A quick check is that breakdowns by product or account should add up to the company total. Answers can also vary between runs, so test each key question more than once.</p><h4>Write prompts that remove ambiguity</h4><p>Small wording changes help:</p><ul><li><strong>“Combined into one total per account”</strong> stops the agent from grouping by product.</li><li><strong>“Using the exact account names from the previous result”</strong> prevents near-miss name matches.</li></ul><p>Include tested example prompts in your user guidance.</p><h3>Conclusion</h3><p>YoY analysis may look like a simple revenue comparison, but implementing it in a semantic-model-driven environment requires careful consideration of the data grain, relationship cardinality, and where the business logic should live.</p><p>By establishing the appropriate <strong>Many-to-One relationship</strong>, defining revenue at the <strong>Order Item grain</strong>, and creating reusable measures for current-year, previous-year, and previous-to-previous-year revenue, we can derive the corresponding YoY growth measures and reuse them across different levels of analysis.</p><p>The result is more than a YoY percentage. It provides a foundation for moving from overall revenue performance to product, account, region, and other dimensional analysis, and ultimately to conversational analysis through Agentforce.</p><p><strong>The key takeaway:</strong></p><p><strong>Define the business logic once at the appropriate grain, establish relationships according to the underlying business structure, and let the dimensions and conversational experience drive the analysis.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eab9ad833f7b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How We Built Semi and Anti Join Logic in Tableau Next to Identify Students Who Didn’t Rebook After…]]></title>
            <link>https://ramdosk92.medium.com/how-we-built-semi-and-anti-join-logic-in-tableau-next-to-identify-students-who-didnt-rebook-after-1d8e41fca049?source=rss-3d44b7a76dc9------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d8e41fca049</guid>
            <category><![CDATA[agentic-analytics]]></category>
            <category><![CDATA[tableaunext]]></category>
            <category><![CDATA[salesforce-data-360]]></category>
            <category><![CDATA[semantics]]></category>
            <category><![CDATA[batchtransform]]></category>
            <dc:creator><![CDATA[Ramdosk]]></dc:creator>
            <pubDate>Sun, 27 Sep 2026 13:13:38 GMT</pubDate>
            <atom:updated>2026-09-27T13:13:38.516Z</atom:updated>
            <content:encoded><![CDATA[<h3>How We Built Semi and Anti Join Logic in Tableau Next to Identify Students Who Didn’t Rebook After Low Ratings</h3><h3>Introduction</h3><p>In my <a href="https://ramdosk92.medium.com/how-we-used-saql-semi-and-anti-joins-to-identify-students-who-didnt-rebook-after-low-ratings-594f05766044">previous article</a>, we used SAQL semi and anti joins in CRM Analytics to identify students who were actively enrolled, had given low ratings in previous courses, and had not booked any activities in their current course.</p><p>As part of our move to Tableau Next, we needed to deliver the same insight on Data 360.</p><p>However, we quickly ran into a limitation:</p><blockquote>The Tableau Next semantic layer does not provide semi join or anti join functions.</blockquote><p>This meant there was no direct way to:</p><ul><li>Keep only records that have a match, without duplicating them</li><li>Keep only records that do not have a match</li></ul><p>A workaround was needed. However, the transformations required for this workaround (deduplication, aggregations and multiple joins with filters) are beyond what the semantic layer is designed to handle.</p><p>So we moved all the transformation logic into a <strong>Data 360 Batch Transform</strong>, and the solution architecture became:</p><ol><li>Build the semi and anti join workaround in a Data 360 Batch Transform</li><li>Write the result into a curated dataset, registered as a new DLO</li><li>Bring the curated DLO into the Tableau Next semantic layer</li><li>Build the visualizations and dashboard on top of the semantic model</li></ol><p>With this setup, the heavy logic runs in Data 360 and the semantic layer stays simple.</p><p>In this article, we walk through how we rebuilt both joins using standard Batch Transform nodes, and how the result powers KPI cards and agent-ready insights in Tableau Next.</p><h3>The Data Model Behind the Problem</h3><p>We used the same three datasets from our <a href="https://ramdosk92.medium.com/how-we-used-saql-semi-and-anti-joins-to-identify-students-who-didnt-rebook-after-low-ratings-594f05766044">previous article</a>, brought into Data 360 as <strong>Data Lake Objects (DLOs)</strong>:</p><ul><li><strong>BookingLineDataset</strong>: course enrollments (Enrollment)</li><li><strong>ActivitiesFeedbackDataset</strong>: activity ratings (Experience)</li><li><strong>StudentsActivitiesDataset</strong>: activity bookings (Engagement)</li></ul><h3>Approach</h3><p>The entire logic is built inside a single <strong>Batch Transform</strong>, which writes the final student list into a curated DLO.</p><p>The Batch Transform Join node supports Lookup, Left, Right, Inner, Outer and Cross joins, but does not offer a <strong>semi join</strong> or an <strong>anti join</strong>:</p><ul><li><strong>Semi Join</strong> → keeps records that <strong>have a match</strong></li><li><strong>Anti Join</strong> → keeps records that <strong>do not have a match</strong></li></ul><p>To achieve the same result, we rebuilt both using a simple pattern:</p><blockquote><strong>One record per key + Numeric flag + Left Join + NULL check</strong></blockquote><ul><li><strong>Semi Join Workaround</strong> → Left Join + filter where the flag <strong>IS NOT NULL</strong> → a match exists</li><li><strong>Anti Join Workaround</strong> → Left Join + filter where the flag <strong>IS NULL</strong> → no match exists</li></ul><p>The numeric flag is the key to this approach. It always has a value when a matching record exists, so after the Left Join, a NULL can only mean <strong>no match</strong>.</p><p>Using this pattern, the Batch Transform is structured in four stages:</p><ol><li>Identify students currently enrolled in active courses</li><li>Identify students who have given low activity ratings</li><li>Combine these groups to isolate active students with poor past experience (<strong>Semi Join Workaround</strong>)</li><li>Evaluate current course engagement using a custom key (Student + School) (<strong>Anti Join Workaround</strong>)</li></ol><h3>Step-by-Step Logic</h3><p><strong>Step 1 — Identify Current Active Course Students</strong></p><p>We begin by filtering the booking data to students who are currently enrolled in an active course.</p><ul><li>Course has already started</li><li>Course has not yet ended</li><li>Booking status is Active</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*ECT-oIZk4JfTD8a7E9-_1w.png" /><figcaption>Active Course FIlter</figcaption></figure><p>This forms the base population for analysis.</p><p><strong>Step 2 — Identify Students with Low Activity Ratings</strong></p><p>Next, we filter the feedback data to keep only low ratings.</p><ul><li>Ratings below the defined threshold (3.5) are treated as low</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/290/1*SyRebOBYoIOXs2yXyvsJjw.png" /><figcaption>Low Rating Filter</figcaption></figure><p>This highlights students who have experienced dissatisfaction.</p><p><strong>Step 3 — Reduce Low Ratings to One Record per Student</strong></p><p>A student can have multiple low ratings. We create a numeric flag on each low-rating record, then use an Aggregate node to reduce them to one record per student.</p><ul><li><strong>Numeric Flag</strong> → value 1 on every low-rating record</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*Ro8UTtLn-5NkNMUdeK1nQw.png" /><figcaption>Numeric Flag</figcaption></figure><ul><li><strong>Aggregate</strong> → group by Booking Account and sum the numeric flag</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/1*J-2t8yM8YgNetMoyYNClZQ.png" /><figcaption>Aggregation node</figcaption></figure><blockquote><strong>Why this matters:</strong> Without this step, the join would repeat a student once for every low rating. The aggregated flag created here is what Step 4 uses to detect whether a match exists.</blockquote><p><strong>Step 4 — Identify Active Students with Low Ratings (Semi Join Workaround)</strong></p><p>We now join the active students from Step 1 with the one-record-per-student low-rating data from Step 3.</p><p>The goal is to keep <strong>only active students who have at least one low rating</strong>, with each student appearing once.</p><p><strong>Choosing the join type</strong></p><p>The Join node offers Lookup, Left, Right, Inner, Outer and Cross joins. We use a <strong>Left Join</strong>:</p><ul><li>It keeps <strong>every active student</strong> from the left side</li><li>Where a student has a matching low rating, the right-side columns are filled in</li><li>Where there is no match, the right-side columns are <strong>NULL</strong></li></ul><p>This NULL is what we use to tell students with a low rating apart from students without one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/1*IJAKjVBt7d3asGOeKVyC4A.png" /><figcaption>Low activity Score on to Active Course Student</figcaption></figure><p><strong>Keeping only the matches</strong></p><p>We then filter on the numeric flag created in Step 3,keeping only records where it <strong>IS NOT NULL.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*H7roTjsCe_Q5UcG7Nt40fg.png" /><figcaption>Semi Join Filter</figcaption></figure><p>We filter on the numeric flag rather than any other right-side column because the flag always has a value when a match exists. A NULL here can only mean no low rating exists.</p><p>This ensures we retain only:</p><ul><li>Students who are currently active</li><li>And have at least one low rating</li></ul><p><strong>Step 5 — Create a Custom Key for Course-Level Comparison</strong></p><p>We create a custom key on the semi-joined datastream:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*rnxbIO7OLr1WFKxcoz5iog.png" /><figcaption>Custom Key</figcaption></figure><p><strong>Why this matters:</strong> Students can enroll in multiple courses across different schools. The custom key makes sure we check activity bookings for the <strong>current course only</strong>, not for any course.</p><p><strong>Step 6 — Prepare Activity Booking Data</strong></p><p>We process the activity booking data to identify students who have booked activities.</p><ul><li>Filter only records with status = “Booked”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/331/1*p9DsVPgdiGNeTgcfMkUg_w.png" /><figcaption>Booked Activity Filter</figcaption></figure><ul><li>Create the same custom key</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*3MMWgoPBeqyR9r54kGLo7w.png" /><figcaption>Custom Key</figcaption></figure><ul><li>Create a numeric flag (value 1)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*yIEaFeNvTk3ffHwyTvUm1Q.png" /><figcaption>Activity Numeric Flag</figcaption></figure><ul><li>Aggregate activity bookings by student and school</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/333/1*n4x_vJxM-8wT3WM024BQDw.png" /><figcaption>School Wise Student Activity Booking aggregation</figcaption></figure><p>This results in one record per student per school, with the number of activities booked.</p><p><strong>Step 7 — Identify Students Without Activity Bookings (Anti Join Workaround)</strong></p><p>Finally, we join the result from Step 5 (active students with low ratings, with a custom key) with the aggregated activity data from Step 6.</p><p>The goal is to keep <strong>only the students who have no activity booking in their current course</strong>.</p><p><strong>Choosing the join type</strong></p><p>We use a <strong>Left Join</strong> again, for the same reason:</p><ul><li>It keeps <strong>every student</strong> from the semi join result</li><li>Students who booked activities get a value in No_of_Activity</li><li>Students who did not book any activity get <strong>NULL</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*aJM3wZZruwvA6HNJm6b-vw.png" /><figcaption>Student Activity booking onto Active Course</figcaption></figure><p><strong>Keeping only the non-matches</strong></p><p>We then filter on the activity count created from the numeric flag in Step 6,keeping only records where it <strong>IS NULL.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*UrBz-ad8IpStw7NrGYUWNg.png" /><figcaption>Anti Join Filter</figcaption></figure><p>The remaining students:</p><ul><li>Are active</li><li>Have had poor past experiences</li><li>Have not booked any activities in their current course</li></ul><p><strong>Step 8 </strong>— <strong>Clean up and Write the Output</strong></p><p>We remove the helper fields (custom keys, flags, counts) that were only needed for the logic and write the result into a curated DLO.</p><p>Output DLO: <strong>Students not booked activity in current</strong>, with write mode <strong>Overwrite</strong>, so each run replaces the previous result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/443/1*Snqg9qCejhNrXruHFb7bYA.png" /><figcaption>Curated data write DLO Output Node</figcaption></figure><p>Final Data Transform:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nHS8DXxnTCyFaO7bHVNkyg.png" /><figcaption>Data Transform</figcaption></figure><p><strong>Step 9 — Build the Semantic Model in Tableau Next</strong></p><p>With the curated DLO ready, we bring it into the Tableau Next semantic layer and prepare it for visualization.</p><p>This involves:</p><ul><li>Establishing relationships between the Course Booking DLO, the Activity Booking DLO and the curated DLO</li><li>Creating calculated fields where required</li></ul><p><strong>Establish the relationships</strong></p><p>In the semantic model (<em>Students Course Booking</em>), we add all three DLOs and create relationships between them:</p><p><strong>Why this matters:</strong> The curated DLO contains only the students who need attention. The relationship with the Course Booking DLO lets us view them alongside the full currently enrolled population, for example “<em>X out of Y currently enrolled students have not booked any activity</em>”. The Activity Booking DLO completes the picture, showing the activity bookings of engaged students, so the dashboard and the agent can compare students who are engaging with those who are not.</p><p><strong>Create the calculated fields</strong></p><p>We create calculated fields on the DLOs where required, to capture the key business definitions directly in the semantic model.</p><ol><li><strong>Is currently enrolled course Student ?</strong> (on <em>BookingLineDataset</em>)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*1FgHYkbytv6YK8wzQXgCcg.png" /><figcaption>Calculated column</figcaption></figure><p>This field identifies whether a student is currently enrolled in an active course.</p><p><strong>2. Number of Students not booked activities</strong> (on <em>Students not booked activity in current</em>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*VPGzIaBIktcRpgIh6SK2qw.png" /><figcaption>calculated column</figcaption></figure><p>This field counts the distinct students who are currently enrolled, have given a low rating, and have not booked any activity.</p><p><strong>Why these calculated fields matter:</strong></p><ul><li><strong>KPI cards become simple.</strong> The dashboard can show the number of currently enrolled students and the number of students not booked activities directly, without building extra logic in each visualization.</li><li><strong>Agents can answer questions easily.</strong> There is no definition of “students who haven’t booked an activity” anywhere in the semantic layer, and the calculated fields provide that context.</li><li><strong>Counts stay accurate.</strong> Using COUNTD on Booking Account makes sure each student is counted only once.</li><li><strong>The logic is defined once.</strong> Every dashboard and agent built on this semantic model uses the same definition.</li></ul><p><strong>Number of Students not booked activities</strong> tells the agent what the curated DLO represents: each record is a currently enrolled student with a low rating who hasn’t booked any activity. When a user asks <em>“Who are the students that haven’t booked any activity in their current course?”</em>, the agent can identify the right data object and answer from it.</p><p><strong>Is currently enrolled course Student ?</strong> gives the agent a clear definition of an active student. For follow-up questions, such as <em>“What percentage of currently enrolled students haven’t booked an activity?”</em>, the agent can use this flag directly instead of working out the status and week logic itself.</p><p>Clear field names and descriptions are what make this work, so they’re worth writing carefully.</p><h4>Putting It All Together: The Tableau Next Workspace</h4><p>In Tableau Next, a <strong>workspace</strong> brings all the assets for a use case together in one place. For this use case, the <em>Tableau Next Experimentation</em> workspace holds all <strong>9 assets</strong>, from the source data through to the final dashboard:</p><p>At a glance: <strong>4 Data Objects</strong> (3 source DLOs and 1 curated DLO), <strong>1 Data Transform</strong>, <strong>1 Semantic Model</strong>, <strong>2 Visualizations</strong> and <strong>1 Dashboard</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p7IUDIMEMJGiWOHj_hhmjQ.png" /><figcaption>Workspace</figcaption></figure><pre>Source DLOs → Batch Transform → Curated DLO → Semantic Model → Visualizations → Dashboard</pre><p><strong>Why this structure matters:</strong> Each layer has one clear responsibility. The Batch Transform handles the complex logic, the semantic model defines the business meaning, and the visualizations and dashboard focus only on presenting the insight. This makes the solution easier to maintain, reuse and extend.</p><h3><strong>Final output:</strong></h3><p>The dashboard shows that <strong>6 out of 24 currently enrolled students (25%)</strong> have given a low rating and have not booked any activity in their current course.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IHVsWBdWk8SN4-Qoycb1fQ.png" /><figcaption>Dashboard</figcaption></figure><h3>See It in Action</h3><p>The KPI cards answer the headline numbers. In the video below, we go further and ask the agent follow-up questions about these students, answered using the calculated fields in the semantic model.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplayer.vimeo.com%2Fvideo%2F1230656310%3Fapp_id%3D122963&amp;dntp=1&amp;display_name=Vimeo&amp;url=https%3A%2F%2Fvimeo.com%2F1230656310%3Ffl%3Dtl%26fe%3Dec&amp;image=https%3A%2F%2Fi.vimeocdn.com%2Fvideo%2F2205607578-c3b6b9923fc33d36d2c9e1a208d043cdb2f3c909fc7123f915c340d1726deca4-d_1280%3Fregion%3Dus&amp;type=text%2Fhtml&amp;schema=vimeo" width="1920" height="1080" frameborder="0" scrolling="no"><a href="https://medium.com/media/424cc8d506cd23e7e550a73892261da1/href">https://medium.com/media/424cc8d506cd23e7e550a73892261da1/href</a></iframe><h3>Final Thought</h3><p>Semi and anti joins may not be available as ready-made functions, but the logic behind them can still be built.</p><p>With one record per key, a numeric flag and a Left Join, we can identify both <strong>what exists</strong> and <strong>what doesn’t</strong>, and turn that gap into insight that dashboards and agents can act on.</p><p><strong>What happened before → with → what didn’t happen next</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d8e41fca049" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How We Used SAQL Semi and Anti Joins to Identify Students Who Didn’t Rebook After Low Ratings]]></title>
            <link>https://ramdosk92.medium.com/how-we-used-saql-semi-and-anti-joins-to-identify-students-who-didnt-rebook-after-low-ratings-594f05766044?source=rss-3d44b7a76dc9------2</link>
            <guid isPermaLink="false">https://medium.com/p/594f05766044</guid>
            <category><![CDATA[custom-key]]></category>
            <category><![CDATA[semi-join]]></category>
            <category><![CDATA[anti-join]]></category>
            <category><![CDATA[multi-data-stream]]></category>
            <category><![CDATA[saql]]></category>
            <dc:creator><![CDATA[Ramdosk]]></dc:creator>
            <pubDate>Mon, 21 Sep 2026 20:56:07 GMT</pubDate>
            <atom:updated>2026-09-21T20:56:07.544Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Most analytics dashboards focus on current performance indicators such as active students, activity bookings, and course progression.</p><p>However, they often overlook a critical question:</p><blockquote>Why do some students stop engaging despite being actively enrolled?</blockquote><p>During analysis, we observed a recurring pattern.</p><p>A subset of students enrolled in active courses were not booking any activities. At first, this appeared to be normal variation. However, further investigation revealed a consistent trend.</p><p>These students had:</p><ul><li>Participated in previous courses across different schools, Booked activities in those courses, Submitted low ratings for their experience.</li></ul><p>In their current course, however, they showed no further engagement.</p><p>They had not booked any activities, despite being active.</p><p>This led to a more focused question:</p><blockquote><strong>Is the lack of engagement in the current course influenced by poor experiences in previous courses?</strong></blockquote><h3>Business Requirement</h3><p>The objective is to identify students who:</p><ul><li>Are currently enrolled in an active course</li><li>Have given low ratings for activities in previous courses</li><li>Have not booked any activities in their current course</li></ul><p>This requires connecting historical feedback with current engagement to detect early signs of disengagement.</p><h3>The Data Model Behind the Problem</h3><p>To address this requirement, we worked with three key data entities:</p><ul><li><strong>Course Booking (Booking Table)</strong><br> Contains student enrollment details, including course timelines, booking status, and school information.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*UszIqEpXVB4LMZvk-ULIcw.png" /><figcaption>Sample Booking data</figcaption></figure><ul><li><strong>Feedback (Ratings Table)</strong><br> Captures activity ratings submitted by students, linked to activity bookings.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/1*npT22ywxkYRCjFtaJ-SIGg.png" /><figcaption>Sample Activity Feedback Rating Data</figcaption></figure><ul><li><strong>Activity Booking (Activity Table)</strong><br> Tracks activities booked by students under each course, along with their current status.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*5LcYR5N5-pV-Ww8jWbnf8A.png" /><figcaption>Sample Activity Data</figcaption></figure><p>Each entity represents a different stage of the student journey:</p><ul><li>Enrollment</li><li>Experience</li><li>Engagement</li></ul><h3>Approach</h3><p>To solve this problem, we structured the analysis into multiple logical data streams, each addressing a specific part of the requirement.</p><p>The key challenge was evaluating engagement <strong>within the correct course context</strong>, since students can enroll in multiple courses across different schools.</p><p>A direct comparison using booking identifiers alone would not be sufficient.</p><p>To address this, we designed the solution in four stages:</p><ol><li>Identify students currently enrolled in active courses</li><li>Identify students who have given low activity ratings</li><li>Combine these groups to isolate active students with poor past experience</li><li>Evaluate current course engagement using a <strong>custom key (student + school)</strong></li></ol><p>This ensures that engagement is measured accurately at the course level.</p><h3>Step-by-Step Logic</h3><h3>Step 1 — Identify Current Active Course Students</h3><p>We begin by selecting students who are currently enrolled in active courses.</p><p>The criteria include:</p><ul><li>Course has already started</li><li>Course has not yet ended</li><li>Booking status is Active</li></ul><pre>-- STREAM 1: Active Students (Current Course)<br><br>active = load &quot;BookingLineDataset&quot;;<br><br>active = filter active by &#39;Status_Code&#39; == &quot;Active&quot;;<br>active = filter active by &#39;Booking_Start_Week&#39; &lt;= 2615; <br>active = filter active by &#39;Booking_End_Week&#39; &gt; 2615;<br><br>active = foreach active generate &#39;Booking_Account&#39; as &#39;accId&#39;,&#39;Booking_Student_Name&#39; as &#39;studentName&#39;,&#39;School_Code&#39; as &#39;schoolCode&#39;,&#39;Booking_Name&#39; as &#39;bookingName&#39;;</pre><p>This forms the base population for analysis.</p><p>Output :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*s2809zXHYK6Am5V8HXfdEA.png" /><figcaption>Step 1 output</figcaption></figure><h3>Step 2 — Identify Students with Low Activity Ratings</h3><p>Next, we identify students who have submitted low activity ratings across any course.</p><ul><li>Only valid ratings are considered</li><li>Ratings below the defined threshold (e.g., 3.5) are treated as low</li></ul><pre>-- STREAM 2: Students with Low Activity Ratings<br><br><br>lowRating = load &quot;ActivitiesFeedbackDataset&quot;;<br><br>lowRating = filter lowRating by &#39;Activities_Feedback_Score&#39; is not null;<br>lowRating = filter lowRating by &#39;Activities_Feedback_Score&#39; &lt; 3.5;<br><br>lowRating = foreach lowRating generate &#39;Booking_Account&#39; as &#39;accId&#39;;</pre><p>This highlights students who have experienced dissatisfaction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/258/1*_ZDkI6ZwB5XqPVKKfk4gWQ.png" /><figcaption>Step 2 Output</figcaption></figure><h3>Step 3 — Identify Active Students with Low Ratings (Semi Join)</h3><p>We perform a <strong>semi join</strong> between active students and low-rating students using the student identifier.</p><p>This ensures we retain only:</p><ul><li>Students who are currently active</li><li>And have at least one low rating</li></ul><pre>-- STREAM 3: Active Students with Low Ratings (SEMI JOIN)<br><br>activeLow = join active by (&#39;accId&#39;) semi, lowRating by (&#39;accId&#39;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/317/1*8HnFpRMPI7rYgn-VVd3tqg.png" /><figcaption>Semi Join Output</figcaption></figure><h3>Step 4 — Create a Custom Key for Course-Level Comparison</h3><p>Since students can enroll in multiple courses across different schools, we introduce a <strong>custom key</strong>:</p><p><strong>Student Name + School Code</strong></p><p>This key allows us to:</p><ul><li>Distinguish between different course enrollments</li><li>Evaluate engagement within the correct school context</li></ul><pre>-- STEP 4: Create Custom Key (Student + School)<br><br>activeLow = foreach activeLow generate &#39;accId&#39;,&#39;studentName&#39;,&#39;schoolCode&#39;,&#39;bookingName&#39;,(&#39;studentName&#39; + &quot;-&quot; + &#39;schoolCode&#39;) as &#39;custKey&#39;;</pre><p>The custom key is created in both:</p><ul><li>The semi-joined datastream</li><li>The activity booking datastream</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*7CUQ0xf9TJPY8jmji8QOKw.png" /><figcaption>Step 4 Output</figcaption></figure><h3>Step 5 — Prepare Activity Booking Data</h3><p>We process the activity booking dataset to identify students who have booked activities.</p><ul><li>Filter only records with status = “Booked”</li><li>Create the same custom key</li><li>Group by the custom key</li></ul><pre>-- STREAM 4: Activity Booking Dataset (Grouped by Custom Key)<br><br>activity = load &quot;StudentsActivitiesDataset&quot;;<br><br>activity = filter activity by &#39;Booking_Status&#39; == &quot;Booked&quot;;<br><br>activity = foreach activity generate &#39;Student_Name&#39; as &#39;studentName&#39;,&#39;School_Code&#39; as &#39;schoolCode&#39;,(&#39;Student_Name&#39; + &quot;-&quot; + &#39;School_Code&#39;) as &#39;custKey&#39;;<br><br>-- Group to ensure one record per student per school<br>activity = group activity by &#39;custKey&#39;;<br><br>activity = foreach activity generate &#39;custKey&#39;;</pre><p>This results in a dataset representing <strong>students who have booked activities per school</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/99/1*ag-UkQmwueGJZZVsKarCkQ.png" /><figcaption>Step 5 output</figcaption></figure><h3>Step 6 — Identify Students Without Activity Bookings (Anti Join)</h3><p>Finally, we perform an <strong>anti join</strong> between:</p><ul><li>Active students with low ratings (custom key dataset)</li><li>Activity booking dataset (grouped by custom key)</li></ul><p>This removes students who have already booked activities in their current course.</p><pre>-- FINAL STEP: ANTI JOIN (Students with NO activity booking)<br><br>final = join activeLow by (&#39;custKey&#39;) anti, activity by (&#39;custKey&#39;);<br><br>-- FINAL OUTPUT<br>final = foreach final generate &#39;studentName&#39;,&#39;accId&#39;,&#39;schoolCode&#39;,&#39;bookingName&#39;;<br><br>final = limit final 2000;</pre><p>The remaining students:</p><ul><li>Are active</li><li>Have had poor past experiences</li><li>Have not booked any activities in their current course</li></ul><h3>The Role of Semi and Anti Joins</h3><p>This solution relies on two key SAQL join types:</p><ul><li><strong>Semi Join</strong> → Retains only records that have a match</li><li><strong>Anti Join</strong> → Retains only records that do not have a match</li></ul><p>Together, they enable precise filtering without complex nested logic.</p><p>Final SAQL Code :</p><pre>-- STREAM 1: Active Students (Current Course)<br><br>active = load &quot;BookingLineDataset&quot;;<br><br>active = filter active by &#39;Status_Code&#39; == &quot;Active&quot;;<br>active = filter active by &#39;Booking_Start_Week&#39; &lt;= 2615;<br>active = filter active by &#39;Booking_End_Week&#39; &gt; 2615;<br><br>active = foreach active generate &#39;Booking_Account&#39; as &#39;accId&#39;,&#39;Booking_Student_Name&#39; as &#39;studentName&#39;,&#39;School_Code&#39; as &#39;schoolCode&#39;,&#39;Booking_Name&#39; as &#39;bookingName&#39;;<br><br><br>-- STREAM 2: Students with Low Activity Ratings<br><br><br>lowRating = load &quot;ActivitiesFeedbackDataset&quot;;<br><br>lowRating = filter lowRating by &#39;Activities_Feedback_Score&#39; is not null;<br>lowRating = filter lowRating by &#39;Activities_Feedback_Score&#39; &lt; 3.5;<br><br>lowRating = foreach lowRating generate &#39;Booking_Account&#39; as &#39;accId&#39;;<br><br>-- STREAM 3: Active Students with Low Ratings (SEMI JOIN)<br><br>activeLow = join active by (&#39;accId&#39;) semi, lowRating by (&#39;accId&#39;);<br><br>-- STEP 4: Create Custom Key (Student + School)<br><br>activeLow = foreach activeLow generate &#39;accId&#39;,&#39;studentName&#39;,&#39;schoolCode&#39;,&#39;bookingName&#39;,(&#39;studentName&#39; + &quot;-&quot; + &#39;schoolCode&#39;) as &#39;custKey&#39;;<br><br>-- STREAM 4: Activity Booking Dataset (Grouped by Custom Key)<br><br>activity = load &quot;StudentsActivitiesDataset&quot;;<br><br>activity = filter activity by &#39;Booking_Status&#39; == &quot;Booked&quot;;<br><br>activity = foreach activity generate &#39;Student_Name&#39; as &#39;studentName&#39;,&#39;School_Code&#39; as &#39;schoolCode&#39;,(&#39;Student_Name&#39; + &quot;-&quot; + &#39;School_Code&#39;) as &#39;custKey&#39;;<br><br>-- Group to ensure one record per student per school<br>activity = group activity by &#39;custKey&#39;;<br><br>activity = foreach activity generate &#39;custKey&#39;;<br><br>-- FINAL STEP: ANTI JOIN (Students with NO activity booking)<br><br>final = join activeLow by (&#39;custKey&#39;) anti, activity by (&#39;custKey&#39;);<br><br>-- FINAL OUTPUT<br>final = foreach final generate &#39;studentName&#39;,&#39;accId&#39;,&#39;schoolCode&#39;,&#39;bookingName&#39;;<br><br>final = limit final 2000;</pre><p>Final output :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/1*07fmo6hVSfVdkQ5aSX76pQ.png" /><figcaption>FInal Output</figcaption></figure><h3>Outcome and Business Impact</h3><p>The final output provides a targeted list of students who are likely disengaging due to prior negative experiences.</p><p>This enables teams to:</p><ul><li>Proactively reach out to students</li><li>Recommend suitable activities</li><li>Improve engagement and retention</li><li>Prevent silent drop-offs</li></ul><h3>Performance Considerations</h3><p>While this approach ensures accurate results, performance may be impacted on large datasets due to multiple joins(Semi,Anti).</p><h3>Applicability Beyond This Use Case</h3><p>While this analysis is demonstrated in the education domain, the approach is applicable to any attrition or disengagement scenario.</p><p>The same pattern can be used wherever:</p><ul><li>Users have historical interactions</li><li>Past experiences influence future behavior</li><li>The goal is to detect lack of re-engagement</li></ul><p>Examples include:</p><ul><li>Customers who stop purchasing after a poor experience</li><li>App users who discontinue usage after negative feedback</li><li>Subscribers who do not renew after service issues</li></ul><p>The core logic remains the same.</p><p>The only variation lies in the <strong>custom key</strong>, which defines the business context:</p><ul><li>Customer + Product</li><li>User + Platform</li><li>Account + Service</li></ul><h3>Final Thought</h3><p>At its core, this approach connects:</p><p><strong>What happened before</strong> → with → <strong>what didn’t happen next</strong></p><p>That gap is where early signs of disengagement exist.</p><p>Identifying it early allows organizations to move from reactive reporting to proactive action.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=594f05766044" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Pattern for Reducing Multiple Joins in CRM Analytics — Vol 2: Many-to-Many Relationships]]></title>
            <link>https://ramdosk92.medium.com/design-pattern-for-reducing-multiple-joins-in-crm-analytics-vol-2-many-to-many-relationships-0b41bd227e13?source=rss-3d44b7a76dc9------2</link>
            <guid isPermaLink="false">https://medium.com/p/0b41bd227e13</guid>
            <category><![CDATA[many-to-many-relationship]]></category>
            <category><![CDATA[reduce-join]]></category>
            <category><![CDATA[data-recipe]]></category>
            <category><![CDATA[window-functions]]></category>
            <dc:creator><![CDATA[Ramdosk]]></dc:creator>
            <pubDate>Sat, 20 Jun 2026 06:03:38 GMT</pubDate>
            <atom:updated>2026-06-20T06:03:38.639Z</atom:updated>
            <content:encoded><![CDATA[<p>Surfacing Competitor Intelligence at the Opportunity Level Without Extra Join Nodes Using Composite Keys and Window Functions</p><h3>Introduction</h3><p>This blog post walks through a real-world business scenario that seems straightforward on the surface: <em>show competitor names at the opportunity level in a dashboard</em>. But when you dig into the data model and the many-to-many relationship between opportunities and competitors, things get interesting fast.</p><p>The conventional approach would require multiple joins, which are expensive operations in CRMA. Instead, I’m going to walk you through a smarter workaround using window functions – specifically `COLLECT_LIST` and `LAST_VALUE` – to derive both primary and non-primary competitor information at the opportunity level, all while minimizing join operations.</p><h3>Business Use Case</h3><p>A sales organization wants to see competitor intelligence surfaced directly on their opportunity dashboard in CRMA. Specifically, they need to know:</p><ul><li>Who is the primary competitor for each opportunity (only one per opportunity)?</li><li>Who are the non-primary competitors for each opportunity (can be many)?</li></ul><h3>The Data Model</h3><p>Three objects are at play:</p><h4>Opportunity</h4><p>The core sales object. Each record represents a deal being pursued.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*vuvozBcgygB2s2BBpG27pA.png" /><figcaption>Sample data</figcaption></figure><h4>Competitor</h4><p>A custom object containing competitor profile information – names, categories, strengths, and so on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*os6La_j-_V51VxlFcFdBDQ.png" /><figcaption>Sample data</figcaption></figure><h4>Competitor Solutions (Junction Object)</h4><p>The bridge between Opportunity and Competitor. Each record on this object represents one competitor associated with one opportunity. A key field here is Primary Competitor – a boolean flag (True/False) that identifies whether a competitor is the primary competitive threat for that opportunity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*kWUzffNoqR4eKRp8ZGz1Tg.png" /><figcaption>Sample data</figcaption></figure><p>The business rules are:</p><ul><li>One opportunity can have <em>one primary competitor</em> (Primary Competitor = True)</li><li>One opportunity can have <em>multiple non-primary competitors</em> (Primary Competitor = False)</li><li>An opportunity may have <em>no primary competitor</em> at all</li><li>An opportunity may have <em>no non-primary competitor</em> at all</li></ul><p>This many-to-many relationship is what makes the recipe complex. To display both primary and non-primary competitor names as columns on an opportunity record, you need to flatten this relationship intelligently – without paying the price of multiple expensive joins.</p><h3>The Challenge</h3><p>The source object is Competitor Solutions, which is a junction object between Opportunity and Competitor. This means:</p><ul><li>It contains multiple records per Opportunity</li><li>Each record represents one competitor associated with that opportunity</li><li>The `Primary_Competitor` flag adds a business rule layer – only one competitor per opportunity can be marked True, but many can be False</li></ul><p>So for each Opportunity, we must:</p><ul><li>Identify the single primary competitor name</li><li>Collect all non-primary competitor names into one multi-value field</li><li>Bring both values into the Opportunity data stream as separate columns</li></ul><h3>The Tempting (but Inefficient) Design</h3><p>A very common approach looks like this:</p><ol><li>Filter Competitor Solutions where Primary Competitor = True</li><li>Join Competitor to get the primary competitor name</li><li>Filter Competitor Solutions where Primary Competitor = False</li><li>Roll up non-primary competitor names</li><li>Join primary competitor result to Opportunity</li><li>Join non-primary competitor result to Opportunity</li></ol><p>While this approach is straightforward to think about, it introduces architectural inefficiencies:</p><ul><li>The Competitor Solutions dataset is split into two parallel streams, leading to redundant processing of the same records</li><li>Both streams are then joined back to the Opportunity data stream separately, increasing join complexity and execution cost</li></ul><p>As the recipe evolves, this design pattern often results in:</p><ul><li>Slower execution caused by redundant data streams and repeated joins</li><li>Overly complex recipe graphs that are difficult to debug and extend</li><li>Reaching the platform’s join node limits, restricting future scalability</li></ul><h3>Design Principle</h3><blockquote>If multiple metrics can be derived from the same data stream, compute them together and join only once</blockquote><p>Instead of splitting the Competitor Solutions dataset into separate primary and non-primary streams, we can derive both values within a single stream by combining two techniques:</p><ul><li>A composite key (Opportunity ID + Primary Competitor flag) to create clean, independent partitions for rollup</li><li>Window functions (`COLLECT_LIST`, `LAST_VALUE`) to aggregate, propagate, and flag records – all without additional join nodes</li></ul><p>This keeps the recipe graph simple, processes the junction object only once, and joins back to Opportunity in a single st</p><h3>Step-by-Step Solution</h3><h4>Step 1: Join Competitor to Competitor Solutions</h4><p>The first step is foundational. Join the Competitor data stream to the Competitor Solutions data stream on the Competitor ID field.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*NjcdtnPuHwtveRoqeAEDaw.png" /><figcaption>Getting Competitor Name into Competitor solutions object</figcaption></figure><p><strong>What this achieves:</strong> At this point, each record in the Competitor Solutions stream represents a single opportunity-competitor relationship but now enriched with the competitor’s name pulled from the Competitor object.</p><h4>Step 2: Create a Composite Key</h4><p>Here’s where the creative engineering begins. Before we can roll up competitor names, we need to partition our data correctly.</p><p><strong>The problem: </strong>If we simply group by `Opportunity_ID`, both primary and non-primary competitors get lumped together. Rolling them up would produce incorrect results – we’d lose the distinction between the two types.</p><p><strong>The solution: </strong>Create a <strong><em>composite key</em></strong> by concatenating `Opportunity_ID` + `Primary_Competitor__c`.</p><pre>Composite_Key = Opportunity_ID + &quot;_&quot; + Primary_Competitor__c</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/1*iEs8spZkT5TiQw_MtxoMNw.png" /><figcaption>Composite Key</figcaption></figure><p>Since `Primary_Competitor__c` is either `True` or `False`, this composite key produces two distinct groups per opportunity (assuming both types exist):</p><ul><li>`OPP-001_True` → The primary competitor partition</li><li>`OPP-001_False` → The non-primary competitors partition</li></ul><p><strong>Why this matters:</strong> This key is the backbone of the entire approach. It creates clean, predictable partitions that let window functions operate on the right subset of records – keeping primary and non-primary competitors completely separated during rollup.</p><h4>Step 3: Roll Up Non-Primary Competitor Names</h4><p>Now we use the first window function to aggregate competitor names within each partition.</p><p>Window function used:`COLLECT_LIST` wrapped in a `CASE` statement</p><ul><li>Partition by the Composite_key</li><li>Order by Competitor_Solution_ID(Record_ID) Ascending</li></ul><pre>case <br>    when Primary_Competitor = &#39;False&#39;<br>    then array_join(collect_list(&quot;Competitor.Name&quot;),&#39;,&#39;) <br>    <br>    else &#39;&#39;<br>    <br>end</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*yuXD8P65HJrsJdihjc78aA.png" /><figcaption>Non Primary Competitor Array</figcaption></figure><p><strong>How this formula works:</strong> The `CASE` statement acts as a gate before the aggregation happens. It checks the `Primary_Competitor` flag on each record — only when the value is `False` does it collect and join the competitor name into the array. For records where `Primary_Competitor = True`, it returns an empty string instead.</p><p><strong>Why this CASE wrapper is necessary: </strong>Without it, `COLLECT_LIST` operates across both partitions of the composite key — and since the `Is_First_Record` filter in Step 9 retains the `False` partition record for Scenario A, but retains the `True` partition record for Scenario C, the primary competitor’s name would bleed into the non-primary competitors field for those Scenario C opportunities. The CASE wrapper ensures the non-primary competitors field is always empty when the record belongs to the primary competitor partition, regardless of which record survives the final filter.</p><p>For example, for opportunity `OPP-001` with three non-primary competitors the formula produces:</p><p>| Row | Competitor_Name | Primary_Competitor | Formula Result |</p><p>| — — -| — — — — — — — — | — — — — — — — — — -| — — — — — — — — |</p><p>| 1 | Competitor A | False | Competitor A |</p><p>| 2 | Competitor B | False | Competitor A, Competitor B |</p><p>| 3 | Competitor C | False | Competitor A, Competitor B, Competitor C |</p><p>| 4 | Salesforce | True | *(empty)* |</p><p>The last row for each partition will always hold the complete, final array. This is important – we’ll use this in Step 6 to filter down to only the final record.</p><blockquote><strong>Key insight: </strong>Because we’re using the composite key as the partition, the `True` partition (primary competitor) and `False` partition (non-primary competitors) are always kept separate. There’s no risk of mixing competitor types in the array.</blockquote><h4><strong>Step 4: Derive Primary Competitor Name</strong></h4><p>Now for the second window function. We need to bring the primary competitor’s name onto every record within each opportunity, regardless of which partition it belongs to.</p><p>Use a Window function:</p><ul><li>Partition by the Opportunity Id</li><li>Order by Primary_Competitor__c Ascending</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*87OXJJXoDUYLiXDGzOpvSw.png" /><figcaption>Primmary Competitor</figcaption></figure><p><strong>How LAST_VALUE works here: </strong>This function returns the last value in an ordered window frame. By ordering records within each `Opportunity_ID` by the `Primary_Competitor__c` field – which sorts `False` before `True` alphabetically – the `True` record (primary competitor) naturally falls last in the window.</p><p><strong>The effect:</strong> Every record under a given opportunity, whether it’s in the `True` or `False` partition of our composite key, now gets the primary competitor’s name stamped onto it.</p><p><strong>Why this is powerful:</strong>Without any additional join, we’ve propagated the primary competitor name across all records for an opportunity. The `False` partition records now carry both:</p><ul><li>Their own `COLLECT_LIST` array of non-primary competitor names</li><li>The primary competitor name from `LAST_VALUE`</li></ul><p>This is the core of the optimization – we’re using window functions to effectively “cross-pollinate” information between partitions, eliminating the need for a separate join.</p><h4>Step 5: Fallback Logic for Opportunities Without a Primary Competitor</h4><p>Here’s a critical edge case. What happens when an opportunity has no primary competitor?</p><p>If `LAST_VALUE` finds no `True` record within an opportunity’s window, it falls back to the last non-primary competitor name alphabetically – which is incorrect and misleading.</p><p><strong>The fix: </strong>Wrap the `LAST_VALUE` logic in a `CASE` statement:</p><pre>case <br>    when last_value(Primary_Competitor) = &#39;True&#39;<br>    then last_value(&quot;Competitor.Name&quot;)<br>    <br>    else &#39;&#39;<br>    <br>end</pre><p><strong>How this works: </strong>For each opportunity, we first check whether the last value of the `Primary_Competitor__c` field in the window is `True`. If yes, we confidently return the competitor name – because we know a primary competitor exists and is the last record in the ordered window. If no, we return an empty string, ensuring we don’t accidentally surface a non-primary competitor name in the primary competitor column.</p><p>This fallback logic is subtle but essential for data accuracy. Without it, dashboards would show incorrect primary competitor names for any opportunity that has non-primary competitors but no designated primary.</p><p><strong>Step 6: Flag the Last Record Per Composite Key Partition</strong></p><p>Recall from Step 3 that `COLLECT_LIST` produces an incremental array – the final, complete array only exists on the last record within each composite key partition.</p><p>We need a way to identify that last record reliably.</p><p>Window function used:</p><ul><li>Partition by the Composite_key</li><li>Order by Competitor_Solution_ID(Record_ID) Ascending</li></ul><pre>case <br>    when last_value(Competitor_Solution_ID) = Competitor_Solution_ID<br>    then &#39;Yes&#39;<br>    <br>    else &#39;No&#39;<br>    <br>end<br></pre><blockquote>The window functions partition by and Order by should be same as Step 3 .</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/1*a6CToyd0KNBYBr14GqWcFA.png" /><figcaption>Last Records in thr opportunity subgroup Flag</figcaption></figure><p>At this point, the dataset has all the information we need. The next step is just filtering it down to the right shape for joining.</p><h4>Step 7: Filter Out Partition Records Dynamically</h4><p>Now it’s time to reduce the dataset by eliminating all intermediate incremental rows produced by `COLLECT_LIST` in Step 3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/269/1*toaZEnWthHxKZTUafjuf2w.png" /><figcaption>Last Records Filter</figcaption></figure><p>Recall that `COLLECT_LIST` builds an array incrementally — each row within a composite key partition holds a growing list, and only the final row holds the complete array. By applying this filter, we discard all the in-progress rows and retain only the meaningful last record per partition.</p><p>What the data looks like at this point:</p><p>After this filter, each opportunity will have at most two records — one per composite key partition:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iEuOT3jUeu9eibaZAdPuDg.png" /><figcaption>Filter 1 Output</figcaption></figure><p>The dataset is now compact and ready for the next stage of processing.</p><h4>Step 8: Create a Dynamic Flag to Handle All Opportunity Scenarios</h4><p>At this point we have a clean, compact dataset — but we still have up to two records per opportunity when both primary and non-primary competitor present. We need exactly one record per opportunity to join back to the Opportunity stream. This is where we need to think carefully.</p><p>To handle all scenarios dynamically, we introduce a new window function :</p><p>Window function used:</p><ul><li>Partition by the Opportunity Id</li><li>Order by Primary_Competitor Ascending</li></ul><pre>case <br>    when first_value(Competitor_Solution_ID) = Competitor_Solution_ID<br>    then &#39;Yes&#39;<br>    <br>    else &#39;No&#39;<br>    <br>end</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/1*C7ESJph23VjfEdw2K7nzXw.png" /><figcaption>First records in the opportunity subgroup Flag</figcaption></figure><p>`ORDER BY Primary_Competitor` sorts values alphabetically within each opportunity’s window. Since `False` comes before `True` alphabetically, the `False` partition record always ranks first when both exist. When only one partition exists, that single record naturally ranks first regardless of its value.</p><p>This retains exactly one record per opportunity across all scenarios. Let’s walk through what each opportunity now looks like after this flag:</p><ul><li><strong>Scenario A</strong> — The `False` partition record is kept. It holds the complete non-primary competitor array from `COLLECT_LIST` and the primary competitor name from `LAST_VALUE`. Both values are available on a single record</li><li><strong>Scenario B</strong> — The only `False` partition record is kept. It holds the non-primary competitor array and an empty primary competitor name from the fallback logic in Step 5</li><li><strong>Scenario C</strong> — The only `True` partition record is kept. It holds an empty non-primary competitor array and the primary competitor name</li></ul><p><strong>Why this step is critical:</strong> Without `Is_First_Record`, we would need a hardcoded filter that inevitably excludes one or more scenarios. The dynamic flag ensures every opportunity — regardless of whether it has a primary competitor, non-primary competitors, or both — survives into the final join. No opportunity is silently dropped, and no incorrect records are carried forward.</p><p><strong>Step 9: Filter Competitor Records to One Record Per Opportunity</strong></p><p>With `Is_First_Record` now in place, the final filter is straightforward and self-correcting selection mechanism across all three scenarios.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/267/1*Wl1ZP6_Dzbx4aew8f3sZ2w.png" /><figcaption>First Records filter</figcaption></figure><p>The dataset now has exactly one record per opportunity, carrying all competitor intelligence in two columns, and is ready to join cleanly with the Opportunity data stream.</p><h4>Step 8: Join Back to the Opportunity Data Stream</h4><p>With the Competitor Solutions dataset now reduced to one record per opportunity, a standard left join with the Opportunity data stream is straightforward and efficient.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*opbwq1WCLU1k1rAjyI5Fog.png" /><figcaption>Competitor onto Opportunity Join</figcaption></figure><p>The final dataset has all opportunity fields, plus:</p><ul><li>`Primary_Competitor_Name` – the single designated primary competitor (or empty if none)</li><li>-`Non_Primary_Competitors` – a multi-value array of all other competitors associated with the opportunity</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*PCYExU7cTubBjy9_Ktf_HA.png" /><figcaption>Final Output</figcaption></figure><p>Both columns are now available to surface in CRMA dashboard widgets, lenses, and filters.</p><h3>Summary</h3><p>Why Window Functions Are the Hero Here</p><p>Window functions – `COLLECT_LIST`, `LAST_VALUE`– do the heavy lifting in this approach. Unlike joins, they operate within an existing data stream without exploding row counts or requiring additional data nodes. They let us:</p><ul><li>Aggregate across related records (`COLLECT_LIST`)</li><li>Propagate values across partitions (`LAST_VALUE`)</li><li>Identify specific records within a partition (`FIRST_VALUE`)</li></ul><p>All of this happens in a single, flowing recipe with one join at the beginning and one at the end.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0b41bd227e13" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Pattern for Reducing Multiple Joins in CRM Analytics Data Recipes]]></title>
            <link>https://ramdosk92.medium.com/design-pattern-for-reducing-multiple-joins-in-crm-analytics-data-recipes-193fe5991b42?source=rss-3d44b7a76dc9------2</link>
            <guid isPermaLink="false">https://medium.com/p/193fe5991b42</guid>
            <category><![CDATA[account-history]]></category>
            <category><![CDATA[reducing-joins]]></category>
            <category><![CDATA[data-recipe]]></category>
            <category><![CDATA[design-data-pipeline]]></category>
            <category><![CDATA[pivoting]]></category>
            <dc:creator><![CDATA[Ramdosk]]></dc:creator>
            <pubDate>Sat, 17 Jan 2026 18:21:01 GMT</pubDate>
            <atom:updated>2026-01-17T18:21:01.303Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Practical Approach Using Account Field History</h3><h3>Introduction</h3><p>When working with CRM Analytics Data Recipes, it’s very common to start with a solution that works functionally but slowly becomes hard to maintain and slow to execute as data volume grows.</p><p>One of the most common reasons for this is overusing Join nodes.</p><p>In this article, we’ll walk through a real-world Data Recipe scenario and show how to:</p><ul><li>Avoid unnecessary joins</li><li>Keep the recipe simple and scalable</li><li>Compute multiple “latest field change” metrics in a single history stream</li><li>Join back to the Account dataset only once</li></ul><h3>The Business Scenario</h3><p>We want to calculate the following metrics at the Account level:</p><ul><li>Days since last Owner change</li><li>Days since last Account Rep change</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*quwuYX_QcwDfDFELDJYMow.png" /><figcaption>Sample Data</figcaption></figure><p>the below is the desired Output</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wn2UGaJoBRrRvyJ0xGIp1w.png" /><figcaption>Desired Output</figcaption></figure><h3>The challenge</h3><p>The source object is Account History, which:</p><ul><li>Contains multiple records per Account</li><li>Tracks changes for many different fields</li><li>Can have multiple change records for the same field</li></ul><p>So for each Account, we must:</p><ul><li>Identify the most recent change date for each required field</li><li>Bring both Number of days values into the Account data stream</li></ul><h3>The Tempting (but inefficient) Design</h3><p>A very common approach looks like this:</p><ol><li>Filter Account History for Owner</li><li>Compute latest Owner change date</li><li>Filter Account History for Account Rep</li><li>Compute latest Account Rep change date</li><li>Join Owner result to Account</li><li>Join Account Rep result to Account</li></ol><p>While this approach is easy to think about, it introduces architectural inefficiencies:</p><ul><li>The Account History dataset is split into multiple data streams, which leads to redundant filtering and repeated processing of the same history records.</li><li>These parallel streams are then joined back to the Account data stream more than once, increasing join complexity and execution .</li></ul><p>As the recipe evolves, this design pattern often results in:</p><ul><li>As the recipe evolves, this design pattern often results in:</li><li>Slower execution caused by redundant data streams and repeated joins</li><li>Overly complex recipe graphs that are difficult to debug and extend</li><li>Reaching the platform’s join node limits, restricting future scalability</li></ul><h3>Design Principle</h3><blockquote><em>If multiple metrics can be derived from the same data stream, compute them together and join only once.</em></blockquote><p>Instead of splitting the history dataset into multiple streams, we can derive both metrics in a single stream.</p><p>Below are two valid ways to do this in CRM Analytics Data Recipe.</p><h3>Approach 1: Pivoting Account History Using an Aggregate Node (Recommended)</h3><h3>Step 1: Subset the required history records</h3><p>Since we are going with aggregate solution, Account History records can be aggregated at the Account level by grouping rows by Account Id, grouping columns by Field, and applying a maximum aggregation on the Created Date to identify the latest change per field.</p><p>However, in this use case, the business requirement is to track only two specific fields:</p><ul><li>Owner</li><li>Account_Rep__c</li></ul><p>Processing all history fields would unnecessarily increase execution time and resource usage. To keep the recipe efficient and focused, start by filtering the Account History dataset to include only the required fields.</p><p>This reduces the volume of data flowing through downstream aggregation or window steps and makes the overall recipe easier to execute and maintain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*OmQoWOEUWdTFwGwmu6VmJg.png" /><figcaption>Required field tracking filter</figcaption></figure><h3>Step 2: Convert date to epoch</h3><p>The Aggregate node in CRM Analytics does not support applying aggregation functions directly on date or datetime fields. As a result, functions such as max() cannot be used on CreatedDate in its original format.</p><p>To work around this limitation:</p><ul><li>Convert CreatedDate into a Unix timestamp using a to_unix_timestamp function.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*6OjE8xBXJRGCzmYzzCTIuw.png" /><figcaption>Epoch conversion</figcaption></figure><ul><li>Apply the max() aggregation on the numeric timestamp</li><li>Convert the aggregated value back to a date, if required, in a later step</li></ul><p>This ensures the latest change date is calculated correctly while remaining compatible with the Aggregate node’s capabilities.</p><h3>Step 3: Pivot latest field change dates at the Account level</h3><p>In this step, the Account History records are reshaped so that each Account has a single row containing the latest change date for each tracked field.</p><p>Using an Aggregate node:</p><ul><li>Group Rows By: AccountId</li><li>Group Columns By: Field</li><li>Aggregation: max(timestamp)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*h57FHJftLBqsoWj92y4gqA.png" /><figcaption>Aggregate Node</figcaption></figure><p>This transformation produces:</p><ul><li>One consolidated row per Account</li><li>Separate columns representing the most recent change date for each tracked field</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*_1ettKGLAOtLfMcmDJomDA.png" /><figcaption>Sample output</figcaption></figure><p>By grouping rows by Account and pivoting on the Field column, multiple history records are collapsed into a compact, Account-level view that is ready to be joined back to the Account dataset.</p><h3>Step 4: Calculate Days Since Last Change at the pivot level</h3><p>After pivoting the Account History records using the Aggregate node, missing field changes are represented as zero values, not nulls. This makes the pivoted dataset safe for direct date calculations.</p><p>However, once this dataset is joined back to the Account data stream, any Account that does not have corresponding history records will receive null values for the derived epoch columns. Applying date conversion or datediff logic on these null values at the Account level results in data type mismatch errors and requires additional null-handling logic.</p><p>To avoid this complexity, the “Days Since Last Change” calculation is performed before the join, directly within the pivoted history stream.</p><p>Since null values are not present at this stage:</p><ul><li>Epoch values can be safely converted to Date or DateTime</li><li>datediff can be applied without additional null checks</li><li>The logic remains clean and easier to maintain</li></ul><p>After calculating the day-difference metrics, the result is joined back to the Account dataset using a single join.</p><h4>Choosing the correct date function</h4><p>It is important to use the correct date function based on the data type of the change date field.</p><h4>When the change date is a DateTime</h4><ul><li>Convert the aggregated value back to DateTime</li><li>Use the today() function for the current timestamp</li></ul><p>Example logic:</p><pre>datediff(today(), to_timestamp(latest_change_datetime))</pre><h4>When the change date is a Date</h4><ul><li>Convert the aggregated value to Date</li><li>Use the current_date() function</li></ul><p>Example logic:</p><pre>datediff(current_date(), to_timestamp(latest_change_date))</pre><h4>Why this distinction matters</h4><ul><li>today() returns the current DateTime</li><li>current_date() returns the current Date</li></ul><p>Using mismatched types (Date vs DateTime) can lead to errors or unexpected results in date calculations. Ensuring both inputs to datediff are of the same type keeps the formula predictable and easier to maintain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*bLhPfhipiGv0vzOKV5R-4A.png" /><figcaption>Days Since Last Account Owner Change</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*7JToFetrr7DeEXn7dgEyNA.png" /><figcaption>Days Since Last Account Rep change</figcaption></figure><h3>Why this approach works better</h3><ul><li>Avoids null-related type conversion errors</li><li>Keeps formula logic simple and readable</li><li>Reduces conditional handling at the Account level</li><li>Aligns calculations with the shape of the pivoted data</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*tm5KHfio2KpuVtWrwZYaxg.png" /><figcaption>sample output</figcaption></figure><h3>Step 5: Join once with Account dataset</h3><p>At this stage, the pivoted history stream already contains both “Days Since Last Change” metrics in a single row per Account.</p><p>With all required calculations completed:</p><ul><li>Perform one join back to the Account data stream using Account Id</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*icsG_c1KZwTK62aWb4FJSA.png" /><figcaption>Join Node</figcaption></figure><ul><li>Enrich the Account dataset with both derived metrics in a single step</li></ul><p>By joining only after the metrics are fully derived, the Account-level formulas remain simple and the recipe avoids additional null handling checks.</p><h3>Why this pivot-based approach works well</h3><p>This approach works well because it aligns the recipe design with the shape of the final output while keeping the data recipe simple and efficient.</p><p>1. One stream, one transformation</p><p>All required field-level history logic is handled in a single Account History stream. By pivoting the data at the Account level, multiple change events are consolidated into one record per Account early in the recipe.</p><p>2. Eliminates redundant data streams</p><p>Instead of creating separate history streams for each field, the pivot approach processes the history data only once. This avoids repeated filtering and unnecessary duplication of logic.</p><p>3. Enables a single join to Account</p><p>Since all required metrics are already available in one row per Account, the Account dataset needs to be joined only once. This keeps the recipe graph simple and avoids hitting join-node limits as the recipe evolves.</p><p>4. Simplifies downstream calculations</p><p>By calculating “Days Since Last Change” before the join, the Account data stream remains clean and free from complex null-handling logic. This makes formulas easier to read, test, and maintain.</p><p>5. Scales better as requirements grow</p><p>If additional tracked fields are required in the future, they can be added to the same pivot logic without introducing new joins or parallel streams. The overall recipe structure remains stable even as business requirements expand.</p><h3>Approach 2: Using Window Functions (Alternative)</h3><p>This approach is useful when aggregation alone is not sufficient.</p><h3>Step 1: Filter required fields</h3><p>As before, start with Account History and keep only:</p><ul><li>Owner</li><li>Account_Rep__c</li></ul><h3>Step 2: Create a field-specific grouping key</h3><p>Create a derived field by concatenating:</p><pre>concat(AccountId,Field)</pre><p>This ensures each field’s changes are treated independently per Account.</p><h3>Step 3: Latest Change history records</h3><p>Use a Window function:</p><ul><li>Partition by the custom key</li><li>Order by CreatedDate descending</li></ul><pre>case <br>    when first_value(Id) = Id <br>    then &#39;Yes&#39;<br>    <br>    else &#39;No&#39;<br>    <br>end</pre><p>This identifies the most recent change per field per Account.</p><h3>Step 4: Reduce to latest records</h3><p>Filter:</p><pre>Is Latest Record = Yes</pre><p>At this point:</p><ul><li>Each Account has at most one record per tracked field</li></ul><h3>Step 5: Derive both field values in one row</h3><p>Using window functions again:</p><ul><li>Partition by AccountId</li><li>Order by Field</li><li>Use first() and last() to place both dates into a single row</li></ul><h3>Step 6: Join once with Account dataset</h3><p>After filtering to one row per Account:</p><ul><li>Join the result to the Account dataset</li><li>Calculate the required day-difference metrics</li></ul><h3>When to use this approach</h3><ul><li>When aggregation is not flexible enough</li><li>Number of fields tracking or one or two.</li></ul><p>Although valid, this approach is more complex and should be used only when necessary.</p><h3>Summary :</h3><p>When building CRM Analytics Data Recipes, the way data is shaped and combined has a direct impact on performance, maintainability, and scalability.</p><p>For Account-level metrics derived from history data, it is best to consolidate logic within a single stream using Aggregate nodes whenever the outcome is one row per Account. This avoids unnecessary data splits, reduces join complexity, and keeps the recipe graph manageable as requirements evolve.</p><p>By deriving multiple metrics together and joining back to the Account dataset only once, recipes become easier to understand, easier to maintain, and better suited for production-scale data volumes. Thoughtful design choices early in the recipe prevent performance issues later and make enhancements far less disruptive.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=193fe5991b42" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing Opportunity Stage Progression in CRM Analytics: Why It’s Not a Simple Funnel Metric]]></title>
            <link>https://ramdosk92.medium.com/designing-opportunity-stage-progression-in-crm-analytics-why-its-not-a-simple-funnel-metric-7f48ea79ac64?source=rss-3d44b7a76dc9------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f48ea79ac64</guid>
            <category><![CDATA[custom-sorting]]></category>
            <category><![CDATA[saql]]></category>
            <category><![CDATA[opportunity-progression]]></category>
            <category><![CDATA[multi-data-stream]]></category>
            <dc:creator><![CDATA[Ramdosk]]></dc:creator>
            <pubDate>Sun, 04 Jan 2026 19:22:59 GMT</pubDate>
            <atom:updated>2026-01-04T19:22:59.648Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction:</h3><p>Funnel charts are one of the most commonly used visuals in sales analytics. At first glance, they appear simple — count opportunities at each stage and visualize the pipeline.</p><p>However, when the goal shifts from showing where opportunities currently are to understanding how opportunities progressed through the funnel, the problem becomes significantly complex.</p><blockquote><em>“How many opportunities have progressed through each stage?”</em></blockquote><p>This article explains why opportunity stage progression is not a straightforward calculation, how it differs from simple stage distribution, and how to design a correct, business-aligned progression model step by step.</p><h3>Why Stage Progression Is Not a Straightforward Approach ?</h3><p>At a high level, funnel charts are often used to visualize opportunity stages. However, there is a fundamental difference between opportunity distribution and opportunity progression, and confusing the two leads to incorrect analytics.</p><h4>Distribution vs Progression: A Fundamental Difference</h4><p>Showing current opportunity stages in a funnel represents distribution.</p><p>It answers the question:</p><blockquote>“How is the pipeline currently distributed across stages?”</blockquote><p>This is a current view of the pipeline at a specific point in time.</p><p>Opportunity progression, however, answers a very different question:</p><blockquote>How did opportunities move through each stage, and at which stage did they drop during a given time interval?”</blockquote><p>Progression is about movement and attrition, not just where opportunities exist today.</p><h4>Why Distribution Is Easy to Implement</h4><p>For opportunity distribution:</p><ul><li>Each opportunity has a single Stage value</li></ul><p>We can simply:</p><ul><li>Group by Stage</li><li>Sort stages based on funnel order</li><li>Plot the result in a funnel chart</li></ul><p>This works because distribution depends on a single field.</p><h4>Why Progression Is Harder</h4><p>Opportunity progression does not have a single field that represents it.</p><p>An opportunity’s lifecycle spans multiple stages over time:</p><ul><li>If an opportunity reached Stage3, it necessarily passed Stage2 and Stage1</li><li>If it closed at Stage4, it still contributed to earlier stages</li><li>If it was lost, the stage at which it was lost matters</li></ul><p>Therefore, progression cannot be derived from the current stage alone.</p><p>A progression metric must evaluate:</p><ul><li>How far an opportunity progressed</li><li>Which stages it meaningfully reached</li><li>Where it exited the funnel</li></ul><p>This is where implementation complexity begins.</p><h3>Step-by-Step Solution</h3><h4>Step 1: Define the Stage Model</h4><p>Assume a salesforce default stage cycle</p><pre>Prospecting → Qualification → Needs Analysis → Value Proposition → Id. Decision Makers→ Perception Analysis→Proposal/Price Quote→ Negotiation/Review → (Closed Won / Closed Lost)</pre><p>This stage order becomes the foundation for all progression logic. Opportunities move forward through stages and eventually exit the funnel.</p><h4>Step 2: Identify the Highest Stage Reached</h4><p>To support progression, derive a single value per opportunity:</p><p>Highest Stage Reached</p><ul><li>Open opportunity → current stage</li><li>Closed Won → final stage</li><li>Closed Lost → last active stage before loss (The Stage Prior to Loss field is critical to correctly attribute where drop-offs happen.)</li></ul><p>This value represents the furthest meaningful progression of the opportunity.</p><p>Formula :</p><pre>case <br>    when Is_Closed = &#39;TRUE&#39;<br>    then<br>         case <br>            when Stage_Name = &#39;Closed Won&#39;<br>            then Stage_Name<br>            when Stage_Name = &#39;Closed Lost&#39;<br>            then Stage_Prior_to_Loss<br>            <br>         end<br>    <br>    else Stage_Name<br>    <br>end</pre><p>Create an Highest Reached Stage custom calculated field at Recipe Level.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*A-a4OJ591b0fo8UiGV9RRA.png" /><figcaption>Highest Reached Stage Field</figcaption></figure><h3>Step 3: Apply Stage Threshold Logic</h3><p>For any stage Stage x, include an opportunity if:</p><pre>Highest_Stage_Reached ≥ Stage x</pre><p>This requires creating separate data streams per stage, each applying its own inclusion criteria.</p><p>This rule ensures:</p><ul><li>Open opportunities contribute to all stages they have reached</li><li>Closed-won opportunities appear in all stages they passed</li><li>Closed-lost opportunities contribute only up to the last active stage they reached before loss.</li></ul><p>There are two possible ways to apply stage threshold logic and construct the final progression funnel.</p><h4>Option 1: Apply Stage Threshold Logic at the Recipe Level</h4><p>In this approach:</p><ul><li>Stage threshold logic is applied during data preparation</li><li>A flag is created for each stage (for example, Reached_Stage0, Reached_Stage1, Reached_Stage2, etc.</li><li>These flags are then consumed as individual data streams at the SAQL layer</li><li>The final funnel is built by combining these streams</li></ul><p>However, even with this approach:</p><ul><li>SAQL still requires multiple stage-specific streams</li><li>A union operation is unavoidable</li><li>Creating multiple flags increases recipe complexity and weight</li><li>The recipe becomes harder to maintain without eliminating downstream logic</li></ul><h4>Option 2: Apply Stage Threshold Logic at the Design (SAQL) Layer (Recommended)</h4><p>In this approach:</p><ul><li>Stage threshold logic is applied directly in the SAQL(design) layer</li><li>Separate streams are created for each stage using consistent progression rules</li><li>The funnel is assembled entirely at the SAQL level</li></ul><p>Because the union and stage-wise streams are required regardless, handling progression logic directly in SAQL is the cleaner and more flexible approach.</p><p>For this reason, the remainder of this section focuses on the SAQL-based solution.</p><h4>Step 3.1: Create Stage-Specific Streams with Threshold Logic</h4><p>For each applicable stage in the cycle:</p><ul><li>Create a new stream</li><li>Apply stage threshold logic to retain only opportunities that reached or passed that stage</li></ul><p>SAQL - prospecting stage</p><pre>q = load &quot;opportunity_Progression&quot;;<br><br>--Creating &quot;Prospecting Stage progression calculation data stream&quot;<br>Prospecting = filter q by &#39;Highest_Reached_Stage&#39; in [&quot;Prospecting&quot;, &quot;Qualification&quot;, &quot;Needs Analysis&quot;, &quot;Value Proposition&quot;, &quot;Id. Decision Makers&quot;, &quot;Perception Analysis&quot;, &quot;Proposal/Price Quote&quot;, &quot;Negotiation/Review&quot; , &quot;Closed Won&quot;];</pre><p>At this point, each stream contains only the relevant opportunities for that stage.</p><h4>Step 3.2: Project Required Fields for Each Stage Stream</h4><p>After applying stage threshold logic:</p><ul><li>Opportunities no longer have a single “stage” that represents progression</li><li>Therefore, we must explicitly assign the stage name for funnel visualization</li></ul><p>Assume the stage model:</p><pre>Prospecting → Qualification → Needs Analysis → Value Proposition → Id. Decision Makers→ Perception Analysis→Proposal/Price Quote→ Negotiation/Review → (Closed Won / Closed Lost)</pre><p>For each stream:</p><ul><li>Hardcode the corresponding stage label (for example, “Prospecting”, “Qualification”, “Needs Analysis”) as the stage name</li><li>Project only the required measure fields:</li><li>count(opportunity) if the business cares about volume</li><li>sum(amount) if the business cares about value</li></ul><p>SAQL — prospecting stage :</p><pre>Prospecting = foreach Prospecting generate &quot;Prospecting&quot; as &#39;Stage Name&#39;, &quot;01.Prospecting&quot; as &#39;Sorting Stage Name&#39;,count() as &#39;No of Opportunity&#39;;</pre><p>This process is repeated sequentially:</p><ul><li>First for Prospecting</li><li>Then for Qualification, Needs Analysis, Value Proposition, and so on</li></ul><p>Closed Lost is excluded as a terminal stage because its progression is evaluated using the stage prior to loss.</p><p>Final SAQL of All Stages Data Stream :</p><pre>q = load &quot;opportunity_Progression&quot;;<br><br>--Creating &quot;Prospecting Stage progression calculation data stream&quot;<br>Prospecting = filter q by &#39;Highest_Reached_Stage&#39; in [&quot;Prospecting&quot;, &quot;Qualification&quot;, &quot;Needs Analysis&quot;, &quot;Value Proposition&quot;, &quot;Id. Decision Makers&quot;, &quot;Perception Analysis&quot;, &quot;Proposal/Price Quote&quot;, &quot;Negotiation/Review&quot; , &quot;Closed Won&quot;];<br>Prospecting = foreach Prospecting generate &quot;Prospecting&quot; as &#39;Stage Name&#39;, &quot;01.Prospecting&quot; as &#39;Sorting Stage Name&#39;,count() as &#39;No of Opportunity&#39;;<br><br>--Creating &quot;Qualification Stage progression calculation data stream&quot;<br>Qualification = filter q by &#39;Highest_Reached_Stage&#39; in [&quot;Qualification&quot;, &quot;Needs Analysis&quot;, &quot;Value Proposition&quot;, &quot;Id. Decision Makers&quot;, &quot;Perception Analysis&quot;, &quot;Proposal/Price Quote&quot;, &quot;Negotiation/Review&quot; , &quot;Closed Won&quot;] ;<br>Qualification = foreach Qualification generate &quot;Qualification&quot; as &#39;Stage Name&#39;, &quot;02.Qualification&quot; as &#39;Sorting Stage Name&#39;,count() as &#39;No of Opportunity&#39;;<br><br>--Creating &quot;Needs Analysis&quot; Stage progression calculation data stream&quot;<br>Needs_Analysis = filter q by &#39;Highest_Reached_Stage&#39; in [&quot;Needs Analysis&quot;, &quot;Value Proposition&quot;, &quot;Id. Decision Makers&quot;, &quot;Perception Analysis&quot;, &quot;Proposal/Price Quote&quot;, &quot;Negotiation/Review&quot; , &quot;Closed Won&quot;];<br>Needs_Analysis = foreach Needs_Analysis generate &quot;Needs Analysis&quot; as &#39;Stage Name&#39;, &quot;03.Needs Analysis&quot; as &#39;Sorting Stage Name&#39;,count() as &#39;No of Opportunity&#39;;<br><br>--Creating &quot;Value Proposition&quot; Stage progression calculation data stream&quot;<br>Value_Proposition = filter q by &#39;Highest_Reached_Stage&#39; in [&quot;Value Proposition&quot;, &quot;Id. Decision Makers&quot;, &quot;Perception Analysis&quot;, &quot;Proposal/Price Quote&quot;, &quot;Negotiation/Review&quot; , &quot;Closed Won&quot;];<br>Value_Proposition = foreach Value_Proposition generate &quot;Value Proposition&quot; as &#39;Stage Name&#39;, &quot;03.Value Proposition&quot; as &#39;Sorting Stage Name&#39;,count() as &#39;No of Opportunity&#39;;<br><br>--Creating &quot;Decision Makers&quot; Stage progression calculation data stream&quot;<br>Decision_Makers = filter q by &#39;Highest_Reached_Stage&#39; in [&quot;Id. Decision Makers&quot;, &quot;Perception Analysis&quot;, &quot;Proposal/Price Quote&quot;, &quot;Negotiation/Review&quot; , &quot;Closed Won&quot;];<br>Decision_Makers = foreach Decision_Makers generate &quot;Id. Decision Makers&quot; as &#39;Stage Name&#39;, &quot;04.Id. Decision Makers&quot; as &#39;Sorting Stage Name&#39;,count() as &#39;No of Opportunity&#39;;<br><br>--Creating &quot;Perception Analysis&quot; Stage progression calculation data stream&quot;<br>Perception_Analysis = filter q by &#39;Highest_Reached_Stage&#39; in [&quot;Perception Analysis&quot;, &quot;Proposal/Price Quote&quot;, &quot;Negotiation/Review&quot; , &quot;Closed Won&quot;];<br>Perception_Analysis = foreach Perception_Analysis generate &quot;Perception Analysis&quot; as &#39;Stage Name&#39;, &quot;05.Perception Analysis&quot; as &#39;Sorting Stage Name&#39;,count() as &#39;No of Opportunity&#39;;<br><br>--Creating &quot;Proposal/Price Quote&quot; Stage progression calculation data stream&quot;<br>Proposal_Price_Quote = filter q by &#39;Highest_Reached_Stage&#39; in [&quot;Proposal/Price Quote&quot;, &quot;Negotiation/Review&quot; , &quot;Closed Won&quot;];<br>Proposal_Price_Quote = foreach Proposal_Price_Quote generate &quot;Proposal/Price Quote&quot; as &#39;Stage Name&#39;, &quot;06.Proposal/Price Quote&quot; as &#39;Sorting Stage Name&#39;,count() as &#39;No of Opportunity&#39;;<br><br> --Creating &quot;Negotiation/Review&quot; Stage progression calculation data stream&quot;<br>Negotiation_Review = filter q by &#39;Highest_Reached_Stage&#39; in [&quot;Negotiation/Review&quot; , &quot;Closed Won&quot;];<br>Negotiation_Review = foreach Negotiation_Review generate &quot;Negotiation/Review&quot; as &#39;Stage Name&#39;, &quot;07.Negotiation/Review&quot; as &#39;Sorting Stage Name&#39;,count() as &#39;No of Opportunity&#39;;<br><br> --Creating &quot;Closed Won&quot; Stage progression calculation data stream&quot;<br>Closed_Won = filter q by &#39;Highest_Reached_Stage&#39; in [&quot;Closed Won&quot;];<br>Closed_Won = foreach Closed_Won generate &quot;Closed Won&quot; as &#39;Stage Name&#39;, &quot;08.Closed Won&quot; as &#39;Sorting Stage Name&#39;,count() as &#39;No of Opportunity&#39;;</pre><h4>Step 3.3: Combine All Stage Streams</h4><p>Once all stage-specific streams are prepared:</p><ul><li>Union all streams into a single dataset</li><li>Group by the hardcoded stage name</li><li>Aggregate the required measures (count, amount, or both)</li></ul><p>SAQL :</p><pre> --Merging all Stages Data Streams<br>Final = union Prospecting,Qualification,Needs_Analysis,Value_Proposition,Decision_Makers,Perception_Analysis,Proposal_Price_Quote,Negotiation_Review,Closed_Won;<br>Final = group Final by (&#39;Stage Name&#39;,&#39;Sorting Stage Name&#39;);<br>Final = foreach Final generate &#39;Stage Name&#39; as &#39;Stage Name&#39;,&#39;Sorting Stage Name&#39; as &#39;Sorting Stage Name&#39;, sum(&#39;No of Opportunity&#39;) as &#39;Total No of Opportunity&#39;;</pre><p>This produces one consolidated data stream representing the progression funnel.</p><h4><strong>Step 3.4: Order Stages According to the Stage Model</strong></h4><p>Ordering stages in a progression funnel is not as straightforward as sorting by stage name.</p><p>In most real-world implementations:</p><ul><li>Stage names do not follow alphabetical order</li><li>Stage sequences are defined by business-specific sales processes</li><li>Standard stage names may differ from organization to organization</li></ul><p>Because of this, simply applying an alphabetical ORDER BY stage_name will almost always produce an incorrect funnel.</p><h3>Why Ordering Is Simple at the Recipe Level</h3><p>If stage flags are created at the recipe level:</p><ul><li>A numeric prefix can be added to stage names</li><li>Example:</li></ul><pre>01.Prospecting<br>02.Qualification<br>03.Proposal</pre><ul><li>Sorting becomes easy using the prefixed value</li><li>The numeric prefix can later be hidden or removed at the metadata (XMD) level so that only clean stage names appear in the chart</li></ul><p>This approach works well in data preparation but is not directly transferable to the design-layer approach.</p><h3>Ordering Challenge at the SAQL (Design) Layer</h3><p>When stage progression is implemented directly in the design layer:</p><ul><li>Stage names are hardcoded per stream</li><li>We cannot simply prefix stage names with numeric values without affecting visualization</li><li>Alphabetical sorting is unreliable</li></ul><p>To solve this, we need an additional sorting mechanism.</p><h3>Workaround: Introduce a Sorting Stage Column</h3><p>For each stage-specific stream:</p><ol><li>Create an additional derived column during projection:</li></ol><ul><li>This column contains a numeric or sortable value representing stage order</li><li>Example:</li></ul><pre>01.P0<br>02.P1<br>03.P2</pre><p>2. Project both columns:</p><ul><li>stage_name → used for display</li><li>sorting_stage → used only for ordering</li></ul><h3>Apply Sorting After Aggregation</h3><p>After all stage streams are unioned and aggregated:</p><ol><li>Apply an ORDER BY sorting_stage clause to ensure correct funnel order</li><li>Perform a final projection:</li></ol><ul><li>Retain stage_name</li><li>Retain aggregated measures</li><li>Exclude sorting_stage from the final output</li></ul><p>This guarantees:</p><ul><li>Correct stage ordering</li><li>Clean, business-friendly labels on the funnel</li></ul><p>SAQL :</p><pre>Final = order Final by &#39;Sorting Stage Name&#39; asc ;<br>Final = foreach Final generate &#39;Stage Name&#39; as &#39;Stage Name&#39;,&#39;Total No of Opportunity&#39;;</pre><p>At this point, the dataset is ready for funnel visualization.</p><h3>Step 4: Final Funnel Metrics</h3><p>Applying the same threshold logic across stages produces a clean progression funnel:</p><pre>q = load &quot;opportunity_Progression&quot;;<br><br>--Creating &quot;Prospecting Stage progression calculation data stream&quot;<br>Prospecting = filter q by &#39;Highest_Reached_Stage&#39; in [&quot;Prospecting&quot;, &quot;Qualification&quot;, &quot;Needs Analysis&quot;, &quot;Value Proposition&quot;, &quot;Id. Decision Makers&quot;, &quot;Perception Analysis&quot;, &quot;Proposal/Price Quote&quot;, &quot;Negotiation/Review&quot; , &quot;Closed Won&quot;];<br>Prospecting = foreach Prospecting generate &quot;Prospecting&quot; as &#39;Stage Name&#39;, &quot;01.Prospecting&quot; as &#39;Sorting Stage Name&#39;,count() as &#39;No of Opportunity&#39;;<br><br>--Creating &quot;Qualification Stage progression calculation data stream&quot;<br>Qualification = filter q by &#39;Highest_Reached_Stage&#39; in [&quot;Qualification&quot;, &quot;Needs Analysis&quot;, &quot;Value Proposition&quot;, &quot;Id. Decision Makers&quot;, &quot;Perception Analysis&quot;, &quot;Proposal/Price Quote&quot;, &quot;Negotiation/Review&quot; , &quot;Closed Won&quot;] ;<br>Qualification = foreach Qualification generate &quot;Qualification&quot; as &#39;Stage Name&#39;, &quot;02.Qualification&quot; as &#39;Sorting Stage Name&#39;,count() as &#39;No of Opportunity&#39;;<br><br>--Creating &quot;Needs Analysis&quot; Stage progression calculation data stream&quot;<br>Needs_Analysis = filter q by &#39;Highest_Reached_Stage&#39; in [&quot;Needs Analysis&quot;, &quot;Value Proposition&quot;, &quot;Id. Decision Makers&quot;, &quot;Perception Analysis&quot;, &quot;Proposal/Price Quote&quot;, &quot;Negotiation/Review&quot; , &quot;Closed Won&quot;];<br>Needs_Analysis = foreach Needs_Analysis generate &quot;Needs Analysis&quot; as &#39;Stage Name&#39;, &quot;03.Needs Analysis&quot; as &#39;Sorting Stage Name&#39;,count() as &#39;No of Opportunity&#39;;<br><br>--Creating &quot;Value Proposition&quot; Stage progression calculation data stream&quot;<br>Value_Proposition = filter q by &#39;Highest_Reached_Stage&#39; in [&quot;Value Proposition&quot;, &quot;Id. Decision Makers&quot;, &quot;Perception Analysis&quot;, &quot;Proposal/Price Quote&quot;, &quot;Negotiation/Review&quot; , &quot;Closed Won&quot;];<br>Value_Proposition = foreach Value_Proposition generate &quot;Value Proposition&quot; as &#39;Stage Name&#39;, &quot;03.Value Proposition&quot; as &#39;Sorting Stage Name&#39;,count() as &#39;No of Opportunity&#39;;<br><br>--Creating &quot;Decision Makers&quot; Stage progression calculation data stream&quot;<br>Decision_Makers = filter q by &#39;Highest_Reached_Stage&#39; in [&quot;Id. Decision Makers&quot;, &quot;Perception Analysis&quot;, &quot;Proposal/Price Quote&quot;, &quot;Negotiation/Review&quot; , &quot;Closed Won&quot;];<br>Decision_Makers = foreach Decision_Makers generate &quot;Id. Decision Makers&quot; as &#39;Stage Name&#39;, &quot;04.Id. Decision Makers&quot; as &#39;Sorting Stage Name&#39;,count() as &#39;No of Opportunity&#39;;<br><br>--Creating &quot;Perception Analysis&quot; Stage progression calculation data stream&quot;<br>Perception_Analysis = filter q by &#39;Highest_Reached_Stage&#39; in [&quot;Perception Analysis&quot;, &quot;Proposal/Price Quote&quot;, &quot;Negotiation/Review&quot; , &quot;Closed Won&quot;];<br>Perception_Analysis = foreach Perception_Analysis generate &quot;Perception Analysis&quot; as &#39;Stage Name&#39;, &quot;05.Perception Analysis&quot; as &#39;Sorting Stage Name&#39;,count() as &#39;No of Opportunity&#39;;<br><br>--Creating &quot;Proposal/Price Quote&quot; Stage progression calculation data stream&quot;<br>Proposal_Price_Quote = filter q by &#39;Highest_Reached_Stage&#39; in [&quot;Proposal/Price Quote&quot;, &quot;Negotiation/Review&quot; , &quot;Closed Won&quot;];<br>Proposal_Price_Quote = foreach Proposal_Price_Quote generate &quot;Proposal/Price Quote&quot; as &#39;Stage Name&#39;, &quot;06.Proposal/Price Quote&quot; as &#39;Sorting Stage Name&#39;,count() as &#39;No of Opportunity&#39;;<br><br> --Creating &quot;Negotiation/Review&quot; Stage progression calculation data stream&quot;<br>Negotiation_Review = filter q by &#39;Highest_Reached_Stage&#39; in [&quot;Negotiation/Review&quot; , &quot;Closed Won&quot;];<br>Negotiation_Review = foreach Negotiation_Review generate &quot;Negotiation/Review&quot; as &#39;Stage Name&#39;, &quot;07.Negotiation/Review&quot; as &#39;Sorting Stage Name&#39;,count() as &#39;No of Opportunity&#39;;<br><br> --Creating &quot;Closed Won&quot; Stage progression calculation data stream&quot;<br>Closed_Won = filter q by &#39;Highest_Reached_Stage&#39; in [&quot;Closed Won&quot;];<br>Closed_Won = foreach Closed_Won generate &quot;Closed Won&quot; as &#39;Stage Name&#39;, &quot;08.Closed Won&quot; as &#39;Sorting Stage Name&#39;,count() as &#39;No of Opportunity&#39;;<br><br> --Merging all Stages Data Streams<br>Final = union Prospecting,Qualification,Needs_Analysis,Value_Proposition,Decision_Makers,Perception_Analysis,Proposal_Price_Quote,Negotiation_Review,Closed_Won;<br>Final = group Final by (&#39;Stage Name&#39;,&#39;Sorting Stage Name&#39;);<br>Final = foreach Final generate &#39;Stage Name&#39; as &#39;Stage Name&#39;,&#39;Sorting Stage Name&#39; as &#39;Sorting Stage Name&#39;, sum(&#39;No of Opportunity&#39;) as &#39;Total No of Opportunity&#39;;<br><br>--Post Projection sorting to show Stages in proper order <br>Final = order Final by &#39;Sorting Stage Name&#39; asc ;<br><br>--Final Projection with required fields<br>Final = foreach Final generate &#39;Stage Name&#39; as &#39;Stage Name&#39;,&#39;Total No of Opportunity&#39;;</pre><p>These numbers naturally decrease, not because of summation, but because each stage applies a stricter progression condition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NG0kh9U9Y6hwiib8AO9SYA.png" /><figcaption>Stage Progression Funnel Chart</figcaption></figure><h3>Conclusion</h3><p>While stage distribution answers where opportunities are today, progression explains how far opportunities traveled through the funnel and where they dropped off. This distinction makes progression a lifecycle-based metric, not a snapshot.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f48ea79ac64" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>