A Snowflake SQL agent can turn 75% of sales into 100% by filtering too early
To answer “What share of nationwide sales came from the West?”, keep the nationwide rows in the calculation and filter only the result.
A user asks a SQL agent, “What share of nationwide sales came from the West last month?” Suppose the West sold $750 and the East sold $250. The answer is 75%. But a Snowflake query that filters to the West before computing RATIO_TO_REPORT can return 100%. The query runs successfully; it just answers a different question.
Snowflake defines RATIO_TO_REPORT as the current row’s value divided by the sum of values in its window partition. If the input to the window contains only the West’s $750, the denominator is $750. If the input contains both regions, the denominator is $1,000. Snowflake’s own example shows how the denominator changes when the comparison changes from a whole chain to a single province: one store contributes 25% of the chain’s profit but 100% of its province’s profit.
Filter the dates first. Filter the displayed regions last.
For this question, the date range defines what belongs in the denominator. The region defines what the reader wants to see. The example below assumes region_sales already contains one row per region for the requested month. Its $750 and $250 are illustrative, not measured data.
WITH shares AS (
SELECT region,
sales,
SUM(sales) OVER () AS nationwide_sales,
100 * RATIO_TO_REPORT(sales) OVER () AS pct_of_nationwide
FROM region_sales
)
SELECT region, sales, nationwide_sales, pct_of_nationwide
FROM shares
WHERE region = 'West';
This returns the West row with $750 in sales, $1,000 in nationwide sales, and a 75% share. Put the West filter inside shares instead and the expected result is $750 for both sales and the denominator, with a 100% share. Showing the denominator makes the error easier to catch than displaying the percentage alone.
Give the agent a test that forces the distinction
Use a two-region fixture like the one above. Ask both “What share of nationwide sales came from the West?” and “What share of Western sales came from each Western store?” The first answer must retain other regions in the denominator even if it displays only the West. The second should restrict the comparison to Western stores. Check the denominator as well as the percentage. And keep a separate zero-total test: Snowflake documents that RATIO_TO_REPORT returns NULL when the partition sum is zero, not 0%.
sources
- Snowflake SQL reference: RATIO_TO_REPORTdocs.snowflake.com
comments · 0