← Back to Technical blog

Technical article

Why Retention Needs More Than Nested Self-Joins: Advanced Analytics Functions in Practice

Use HQL functions and a SQL baseline to distinguish retention, window returns, and continuous activity.

Nov 25, 2026Technical blogHENGSHI11 min read
HQLRetention AnalyticsBI

Article body

Full article

When a product manager asks how many first-week users come back, analysts need to establish two things. Does the cohort start at registration or first activity? Does return mean activity on day seven, at any time within seven days, or on all seven days? Each definition gives a different numerator. Agree on the definition with a few records before choosing window functions, set aggregation, partition filters, or an advanced function.

1 Define the observation window

Suppose users A, B, and C are active on the baseline date. A is active on both following days, B only on day two, and C on neither. Next-day retention is one user, return on either of the two days is two users, and activity on both days is one user. The two-day return and continuous activity metrics can share a denominator and use different tests for the numerator. If day two’s data is incomplete, mark the window open and calculate after the data arrives.

DefinitionRule to stateCommon sources of error
Day-N retentionIntersect the baseline cohort with users returning on a specific business dayUTC and local time can assign events around midnight to different days
Return within a windowAt least one event in the window for a member of the baseline cohortCount repeated visits by one user once
Continuous activityMeet the condition in every period of the windowDistinguish late ingestion from a day with no activity
Fixed-period comparisonEstablish the cohorts and matching criteria in two defined date rangesUsers may use multiple channels or change channel attribution

2 What advanced functions express

HENGSHI SENSE uses HQL to express dataset and metric calculations. When retention, same-period comparison, accumulation, and moving calculations live in the analytics model, dashboard authors and Data Agent can query the same configured definitions within their permissions. A shared expression and small regression dataset make the results reproducible.

The product manual documents retention, continuous_retention, static_retention, and related rate functions. retention takes relative offsets for the observation period. continuous_retention measures activity in every period of the window. static_retention specifies fixed baseline and comparison date ranges. Place channels and product lines in the relevant chart or model and define cross-channel attribution and deduplication for totals.

This HQL example counts users active on each of the last three calendar days. It assumes a dataset with {user_id} and {event_date} and a chart date dimension at daily grain. For new-user retention, define separate entry criteria, observation period, and denominator.

continuous_retention(
  {user_id},
  day({event_date}),
  dayadd(day({event_date}), -2),
  dayadd(day({event_date}), 0),
  'day'
)

When to use fixed and rolling periods

For two completed campaign periods, supply fixed dates to static_retention and group by membership tier or channel in the visualization. For daily reporting on returns after a baseline date, use retention with relative dates and show the business date. For continuous activity, specify the grain, such as day or week, and consistently handle nulls, duplicate events, and time zone conversion before calculation.

Check the function choice against an example result table. Two events on separate days within a window count as one user for return within a period. Regional totals need deduplication across the full cohort when users cross channels. Show closed and unsettled windows separately so readers can distinguish actual zero activity from incomplete data.

3 Use a standard SQL baseline for acceptance

This example counts users active on the baseline day who returned at least once in the following two days. The date is in the business time zone and the range boundaries are explicit. For activity on both days, count distinct active dates and require two, or verify each day against a complete calendar. Agree on the business definition and compare the SQL baseline with the HENGSHI metric.

WITH cohort AS (
  SELECT DISTINCT user_id
  FROM daily_activity
  WHERE activity_date = '2026-07-01'
), returned AS (
  SELECT DISTINCT user_id
  FROM daily_activity
  WHERE activity_date >= '2026-07-02'
    AND activity_date < '2026-07-04'
)
SELECT COUNT(*) AS cohort_users,
       COUNT(returned.user_id) AS returned_users
FROM cohort
LEFT JOIN returned ON returned.user_id = cohort.user_id;

Deduplicating by user and business day before joining reduces the effect of repeated events. Compare aggregation of raw events with deduplicated daily data and the target engine’s plan. Record scanned data, partition pruning, aggregation input, and elapsed time. Check the execution plan for the actual connection and data.

4 Accumulation, moving windows, and calculations across grains

TaskDocumented function capabilityImplementation checks
Period-to-date accumulationdate_accumulate organizes nested aggregation by reset periodCalendar and fiscal periods, and recalculation after backfill
Moving windowsdate_shift supports aggregation windows with relative date offsetsCalendar completion for missing dates and the denominator of averages
Period comparisonsSelect a documented comparison function and specify periods and filtersLeap days, year boundaries, zero values, and unsettled periods
Cross-grain and statistical calculationsEvaluate documented calculate, lookupvalue, distinct counts, and percentilesChart dimensions, subtotals, join cardinality, and roll-up denominators

Define separately whether to zero-fill or exclude missing dates and how to handle late data. Distinct user counts across channels cannot be added. A user visiting two channels counts once in each channel and once in the combined total. Share the rule across dataset preparation, models, and chart expressions. Test the actual dashboard total separately from chart values at their display grain.

Subtotals, filters, and joins affect denominators

The documentation distinguishes the context behavior of calculate, calculatep, and calculatex. The first can vary with chart dimensions and subtotal context. The second is independent of subtotals and the third is independent of chart dimensions. For a province’s share of regional sales, specify expected denominators at province, region, and overall levels and check each one. Change visible provinces or add a filter and confirm that totals and subtotals are recalculated according to the business rule.

lookupvalue also has grain requirements. To retrieve annual purchases from another dataset in a chart grouped by year, define an annual aggregation in the target dataset, join on year, and retrieve it in the chart. Adding month requires another grain check. For repeated, wide, cross-table analysis, maintain the join in the model so others can verify and reuse it.

date_compare can specify baseline and comparison time expressions. previous uses the chart’s time axis to retrieve the preceding period value. Test year-to-date, month-to-date, and rolling-day results with the same cross-year sample, especially when financial and calendar months differ. Metric rules define how to display zero denominators, empty periods, and periods that have yet to close.

Interpret statistics in the context of the distribution

Medians and percentiles describe skewed distributions, distinct counts measure reach, and correlation and regression examine statistical relationships. For approximate production results, record the implementation, data scope, and accuracy expectations. Check accuracy independently for performance evaluation or financial reconciliation. Verify supported functions against the connection, version, and manuals, and confirm the same baseline before and after acceleration.

5 Move from passing samples to production readiness

Test repeated events, null identifiers, cross-day boundaries, and open observation windows. Check denominators in dashboard totals and rerun the baseline after a connection or acceleration change to confirm accuracy and execution cost. For conversational analytics, document “active,” “returned,” and “continuous” separately in metric descriptions and examples. The business definition makes the calculation interpretable across entry points.

Reconcile boundary cases

CaseExpected behavior
Three events from one user on one dayCount each business user once in both the denominator and return count
Month end, year end, and time zone boundariesDates follow the business calendar and values can be reconciled
Missing business dateDistinguish incomplete data from zero activity
Dashboard subtotals enabledDetail rows and denominators at each level have an identifiable source

Record the test window, date grain, connection version, and final definition. When switching calendars or connections, rerun the same boundary cases and explain differences using the new rules.

About HENGSHI

Founded in 2016, HENGSHI develops Agentic BI for the Data + AI era. Its enterprise analytics platform, HENGSHI SENSE, works with the HENGSHI JARVIS digital employee, the HENGSHI CLI execution engine, and the privately deployable HENGSHI BOX. With a decade in BI and a Powered by Hengshi partner ecosystem, HENGSHI supports software vendors across industries and provides private, trusted AI analytics for business operations and decision-making in manufacturing, finance, retail, public services, and other enterprise settings.

HENGSHI SENSE

Resources, ecosystem, and implementation stories

Explore how teams design and ship analytics with HENGSHI.

Request a trial

Enterprise deployment, embedded delivery, and trial requests can all be handled quickly.