Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(bi): add hierarchical pivots and time-series comparisons (#113377)

Marius Andraede0784a31e5
diff --git a/docs/published/handbook/engineering/data-warehouse.md b/docs/published/handbook/engineering/data-warehouse.md
index 8c1bbeee4f9d..a4e256103f3b 100644
--- a/docs/published/handbook/engineering/data-warehouse.md
+++ b/docs/published/handbook/engineering/data-warehouse.md
@@ -48,7 +48,7 @@ Older saves containing only SQL still open in the SQL editor. Their original she
The worksheet date picker supports rolling windows, fixed ranges, this/last month and quarter, and year to date. **Date** selects the column that receives dashboard date ranges; **No date column** explicitly opts out. A dashboard range replaces the worksheet range. Dashboard property filters combine with worksheet conditions. Event-based tables retain standard PostHog property filtering with any date-column selection, using `{filters.native(date_expression)}` or `{filters.native(null)}` when overriding the default date column. Other tables bind dashboard property keys to worksheet fields, including the property key in a field such as `properties.plan`. Unmapped or ambiguous property keys produce a query error instead of silently applying the wrong filter. Reopen and save older BI worksheets to update their generated SQL with dashboard-aware placeholders.
-The comparison picker adds the previous period or a custom offset, including one year earlier. Tables, bar, line, and area charts support comparisons with up to two dimensions. Previous-period dates align to the current axis, and the legend identifies each period. Both periods use the effective dashboard date range and property filters. Comparisons require a bounded range and turn off when the worksheet switches to all time or an unsupported chart.
+The comparison picker adds the previous period or a custom offset, including one year earlier. Tables, KPI cards, bar, line, and area charts support comparisons with up to two dimensions. Previous-period dates align to the current axis, and the legend identifies each period. Tables and KPI cards show current, previous (or comparison), absolute change, and percentage change for each measure. Percentage change divides the difference by the absolute previous value; a zero or missing previous value displays an empty percentage. A missing period remains empty rather than being inferred as zero. Click current or previous values to explore that period's rows. Both periods use the effective dashboard date range and property filters. Comparisons require a bounded range and turn off when the worksheet switches to all time or an unsupported chart.
Generated comparison queries use `{filters.previous}` (or its column-bound form) for the comparison range and `{filters.compareDate(expr)}` to align date dimensions. Custom native date columns use `{filters.previous.native(expr)}`. Month, quarter, and year dimensions pass their bucket as a second argument to `compareDate`, so month lengths and leap years do not move points into the wrong bucket. `HogQLFilters.compareFilter` supplies the comparison offset; missing offsets use the previous period.
@@ -62,7 +62,11 @@ Direct connections group tables by schema. Search matches table and folder names
## Calculated measures in BI mode
-The **Marks** card offers table calculations per measure: percent of total, running total, difference or percent change from the preceding point, trailing moving average, and rank. **Compute using** selects the dimension to traverse, with the date dimension chosen by default; other dimensions partition the calculation. Moving averages count returned points, including the current point. Missing date buckets are not filled. Calculations run before the result limit, and zero denominators produce empty cells.
+The **Marks** card offers table calculations per measure: percent of total, running total, difference or percent change from the preceding point, trailing moving average, and rank. **Compute using** selects the dimension to traverse, with the date dimension chosen by default; other dimensions partition the calculation. Moving averages use a trailing window including the current point, in ascending order. Partial windows average available non-null values; **Require a full window** leaves the result empty until every point in the window has a value. Calculations run before the result limit, and zero denominators produce empty cells.
+
+**Analysis → Missing dates** defaults to **Observed points only**. **Show gaps** creates empty buckets that occupy a point in the window but do not contribute to an average. **Fill with zero** makes those buckets contribute zero. Filling runs before calculations, separately for each series and comparison period, across the selected date range. It requires one bucketed date dimension matching the worksheet date column and a bounded range. It is available for project and warehouse tables in tables and time-series charts; direct connections do not support it. Saved worksheets and dashboard date overrides retain these semantics.
+
+Pivot tables display every measure beneath nested column headers. Expand or collapse a row or column header to move between hierarchy levels. Collapsed values are reaggregated from source rows, including averages and distinct counts. **Subtotals** also shows the intermediate aggregates while expanded. Row and column grand totals retain their separate controls, and total cells keep drill-down scoped to the visible dimensions. Expansion is local to the view; the worksheet's shelves and settings remain unchanged. Tracking records hierarchy expansion with axis and depth, and adds missing-date and full-window settings to the existing worksheet events.
The **Analysis** card ranks **Top N** categories by a selected measure across the full current date range. **Include "Other"** combines the remaining source rows and re-aggregates them, including averages and distinct counts. Removing the ranking measure turns Top N off. Previous-period comparisons use the current period's category selection. Tables offer a grand total; pivot tables offer row and column grand totals. Both support hierarchy subtotals when an axis has multiple dimensions. Totals re-aggregate source rows; table-calculation cells remain blank on total rows. Summary rows can occupy at most half the result limit, reserving room for detail cells. The BI visualization requests an extra row to determine whether more results exist, then removes it before building tables and charts. Saved SQL and exports retain the worksheet's configured limit. A notice appears only when the response confirms more results beyond that limit, which also applies across comparison periods. Cached results and execution caps may prevent the extra row from being returned.
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 69240dd9bce1..34b40d715c81 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -6398,6 +6398,22 @@ snapshots:
hash: v1.k794b7964.47dc280e27c512035ac74d86134e2b5771f84b1454556c492f6319d9d3ffa29f.l0n9noDhYfjTrpN-tlvi5TJq4RJCDIkUCFKse51o1O4
products-autoresearch-probability-histogram--single-bucket--light:
hash: v1.k794b7964.492095448990e600a399d4212b8fb96e8f95c2e7bdafb3f84d8bdc10467fbf4e.1OfZFFoGzmeH8sxtbwrD-H9bR_n08l9kV63NB2Sv1jU
+ products-business-intelligence-comparison-summary--kpi--dark:
+ hash: v1.k794b7964.f57d81874455ecab234e86bea129aa84be0ab55617e1a3f78e4df5ae0b5bef03.0KX9-_jhsiyC9WxFodb_tR84PkA3Sg_F1zEuQGSIPfw
+ products-business-intelligence-comparison-summary--kpi--light:
+ hash: v1.k794b7964.cbd703c31c3e4f7b3dfefc7a1e4e1545f194ace8a4244d3622c76567fe24656c.zExqWHMx3BUNt1WBrRgODcRNuA2v4gWex4w9yl8DLwQ
+ products-business-intelligence-comparison-summary--kpi-with-breakdowns--dark:
+ hash: v1.k794b7964.dc16632b182babc1c391d8b029bedbfa8de8e4a98cab8d00e1793cfafe4397ed.sOgPhdkDOGgDyKAH-x05m_zH-gUIBcYqU0whwWLyrf0
+ products-business-intelligence-comparison-summary--kpi-with-breakdowns--light:
+ hash: v1.k794b7964.8d2396d7d7d9793af0dae6c603f021c1b702b6dc99b78304888f6eedfe9e67ac.v4Tl2MJml1p4CBQtPEPZQOIUKnM9vkLL_M3jZwEyehg
+ products-business-intelligence-comparison-summary--table--dark:
+ hash: v1.k794b7964.4d9cb89cf4df116ff3e473c6484b641d675a0ea9c42f05bf132ae946b8fb5ca8.7gZROaPmb_dBk2rRnqWl_FEMGXi-hHVdsl42uYiZE44
+ products-business-intelligence-comparison-summary--table--light:
+ hash: v1.k794b7964.2476db083ec4c26dd53dab30351f38104c63d9578cd30eae620b60e8cc22a438.plfjAxTsZmL_nRDwhmqufs8yWeTX0wXrr0u5Is8_RUw
+ products-business-intelligence-pivot-table--multiple-measures-and-hierarchies--dark:
+ hash: v1.k794b7964.b92a13e09ed110143b68de5e967f20864fae45eabdcf41f3e77284a412ecf2fb.9kqmJUDi_54LfCfI0Hqyjz1r16tSdhFCKz1jtY_9sr8
+ products-business-intelligence-pivot-table--multiple-measures-and-hierarchies--light:
+ hash: v1.k794b7964.f3a5839e83ddc9921b021426487c0f0db66fe969bc1369dd799c98bd83c91c19.e4TqncN8iN7TmyLw5M8lgUEjfSjD2LgrVykUPu1Ws48
products-business-intelligence-worksheets--worksheets--dark:
hash: v1.k794b7964.07d353f8f721fee4df50f532e578c185cb89a6e61838a84828b5d6aa8d074933.Vug8TcMYcUt4yrU-GMl8VkVhxa2sYMsjdHIOs3XbW6Q
products-business-intelligence-worksheets--worksheets--light:
@@ -9627,29 +9643,29 @@ snapshots:
scenes-app-data-warehouse-settings-schemas--multi-schema--light:
hash: v1.k794b7964.2f4bd6098d8c54c0b25ed9ee0ef7770a59c4d343191d065b0814299a27a42a22.6jWN3F1ozzMy7KZRTYHY1XPxasFL_u2H8Ybw9WcDjfk
scenes-app-data-warehouse-sql-editor--bi-calculated-measure-editor--dark:
- hash: v1.k794b7964.1c0c14cdee7bfc208f3463612a7258ffb18eab85743802b57a550056c4f13063.ubWAo_M3qsL1pI4N1wkAao5VS5nYOPWSeYNpS_lk0G4
+ hash: v1.k794b7964.1c26a867126bd8f979d25b607a2b97f8ca6c6247af3277a01f3743b70ee79906.2WumIrqVnmCHOdKoSFlfOweHTj1x0mY2uixo5g-bBkE
scenes-app-data-warehouse-sql-editor--bi-calculated-measure-editor--light:
- hash: v1.k794b7964.269c7d97582f9c850fb1a04b18ff407237c23197f1b3bf5c1943f46a1fd15802.tcOzXErjnX_icjhtqI84VAAkHnsarpFsVbe2_nt1eao
+ hash: v1.k794b7964.e372f1acdc4460bd92df4c1d47b1995013566643ede9a4df193fd8519656a31e.0FqHLQiwr1QawwbcwZjh4O5bP0W_DEgWWXRX8etSTUU
scenes-app-data-warehouse-sql-editor--bi-combined-measures--dark:
- hash: v1.k794b7964.45c0fd56c6b085e1a229c0dfd35a4e25462d2a75149b7532d040e31b30ddab0b.qPhdMdfKxNPosoOCX3wJ_Vm_CQuGVbOGktCSowg9Mu4
+ hash: v1.k794b7964.09a8bc2f32bdc11358e8e2e47e8ee27f24c6c685013360f6d1cfa4c1d5b5936f.U-vRC09hHiNsoVqmtEHHk3J22eBn-fsFz_LD87tZX1Q
scenes-app-data-warehouse-sql-editor--bi-combined-measures--light:
- hash: v1.k794b7964.26487b780e4c42f39ad7c3cfbbfb492c1c72c40b65143b0dcab9afe4e98aad02.Xp41xep3O_h5SgMD_bAwFWNDAljTfr6fS2h5PJPIEOc
+ hash: v1.k794b7964.381714c67d398a94e60460022d6d176049b3cd9799d68a6389efffcc73c71dfd.wvz5lIWhFxRTY0Csvsp2HQoIZsF6VWBTkuTwtSP2okE
scenes-app-data-warehouse-sql-editor--bi-connections--dark:
hash: v1.k794b7964.30fa64956a72d0e5ad04915a689ab4ae2f28033b1ccf2ed64aba828fdf72376e.OK5R-iy-rRpBfuvZMttjS35Mk9xbsw2k1lohMWcdPoo
scenes-app-data-warehouse-sql-editor--bi-connections--light:
hash: v1.k794b7964.e94d9579f06adc1ce94daa983313f3ad61d31d719eac7ea7c7e98f464eda46df.OM_zpS2uSuzdRWdOeIunASj-usUdZ2nGj70neegODjI
scenes-app-data-warehouse-sql-editor--bi-data-source-picker--dark:
- hash: v1.k794b7964.6f2e46f7552afbb1f0bda49cc6e4535b7257635b4695e38fe437f690dde859a5.GQzEq7sbnYcMbGLMI7caHm8JAfVwXQdbc4-gdpT6gOo
+ hash: v1.k794b7964.29916b4b2b70a92b1ee1c480674c9df95379037584297bb489ede99415807a03.a4XGwj4B_nCBBOXLgL0csu8w4yW0YkjQK3-9OdHrfBU
scenes-app-data-warehouse-sql-editor--bi-data-source-picker--light:
- hash: v1.k794b7964.a12e98f924a33220030ff2b509f3fe1d5ce2069393d8a6171ac26850e6a3d11f.4OuGkRNpmwzAOpGJtR5XMML4RBS4023RYjt0YA2Ou9M
+ hash: v1.k794b7964.4fdeed1bbd422768c488e936728e0ebd850418076a54086460342cf6763bf533.pEalqCxPAWUuLTg4huXBRzEjd_zVJMyhWpHAn4Ncm-k
scenes-app-data-warehouse-sql-editor--bi-drilldown--dark:
hash: v1.k794b7964.182a98228bfd31547d3da94736c9f4edd46bcf2df159f7b2f205366e1b2861bb.lTR1rIlnk0Fv3y7XjHRI-bvfL6Z7C2O5t3h3pl9yG5A
scenes-app-data-warehouse-sql-editor--bi-drilldown--light:
hash: v1.k794b7964.7c6a504d11a8b8ac5b6520d91e4ba717f8b3cd06a954d63009cd190aba5b81e3.j-8gZpi8prOIMMRnYxkxe4NJV8IujxqYLRUuENWtj4Q
scenes-app-data-warehouse-sql-editor--bi-edit-saved-insight--dark:
- hash: v1.k794b7964.75a1949bbd8748f00d23ddc008119f02da05aa706e249e0de22f52d190573e5d.EEZrbUJMBV-O_uYt1lTdXS46E18VXwX_BRanLkK4wVE
+ hash: v1.k794b7964.a3e27aeaf26aa9cbced69edcf2bd79432b009741a80ac0803ac42d0a014a11ed.K2aPuoBTdiu9licgR3HVVjI0-r8hqwx__zDELafRSVE
scenes-app-data-warehouse-sql-editor--bi-edit-saved-insight--light:
- hash: v1.k794b7964.8a0b77f15ee41eaafd7bd02c480186da594ce65030444d7a4789ef5f63310902.TV_DYJ0uCn9pghwZig4ljMlapMFTgCr3Tdynfwq0TFY
+ hash: v1.k794b7964.02422eb6c6206e94f8f7c0c2fa63e494604bd0f46fab1a29a98ea5037a499c58.qh-YHmBLo0OYAJHhCMSODJIZccX-LVmnnuJAV8EljyI
scenes-app-data-warehouse-sql-editor--bi-empty-worksheet--dark:
hash: v1.k794b7964.02b2c5ef535309fbabbc662d0a18c0aa63186b35a5b2b66d141f0a238d5f11ab.Wkl7IYUP_AQq3I5eRVBzl8fDMvmDEYE6oa9q_iF2_Xc
scenes-app-data-warehouse-sql-editor--bi-empty-worksheet--light:
@@ -9659,33 +9675,33 @@ snapshots:
scenes-app-data-warehouse-sql-editor--bi-measure-display--light:
hash: v1.k794b7964.c50185dcf01dc16647795157545a16269ea79403bd04fc6b63d86d2e9991fd12.6C4Pz3LIrHUbp1LbYcRE2vN_HJjikyQQeonijKS2o1A
scenes-app-data-warehouse-sql-editor--bi-mode-worksheet--dark:
- hash: v1.k794b7964.1465b53318ebd4ee942d581040704a8ddeb4de51ffde9e97156d522a687eb6f3.BdVfCS9JBCZ9M6vpFXcgP8Pt8QypLoWlxasjCUiuESo
+ hash: v1.k794b7964.ba547f3a41ec2e8b517142f1a6549848e39ce50da6245a8185117128424b5fc6.mto7EGXrYQwr6BBCyPfkDZS_fYGuYIb_k6KbIkShjQY
scenes-app-data-warehouse-sql-editor--bi-mode-worksheet--light:
- hash: v1.k794b7964.0510cf589eabe8a04dde3c7d79c8f00aa4d955a90e7fcf98fc1064eb3beb56c7.yRTPbMpWSZqepxgtBV2EKACf9uxXwaK-KmNLop0ohCc
+ hash: v1.k794b7964.f17b0a24d40667261252cd224fc879c6303e143cdb46582ea0c3d58516a96508.B3zMdPmNMyvPT29AsSlyzi2TOsGlD40QZz4jThEmkXY
scenes-app-data-warehouse-sql-editor--bi-one-click-comparison--dark:
- hash: v1.k794b7964.9dc96eb2daf79469feaca37095206831653772abcbc11dbc2b379ef8217dfe2b.LwIwT2PobleBmqlU_x5mAnmqG5Ss9JzkAALIuGaZzLo
+ hash: v1.k794b7964.bf9cdbe93cab7bf8f2cc7bc226082cea7dbc69cffb6496ce7b991b18d42fa682.8qoSKEAsOEoHEg8AbdLRi1olkEjewJKyZgqoQLvIEes
scenes-app-data-warehouse-sql-editor--bi-one-click-comparison--light:
- hash: v1.k794b7964.a236e635d84b889d4434aef46e1d62e88a44ec69b3f7dce7677a609889acb37b.qMwKzI_jQgHg_LDcHYkz_FvhLJpQEJ5lvcOoYPpC1vo
+ hash: v1.k794b7964.4905cca54a8784621c6b308a250aea5189f1174f9bd5ae8a2b3ffcb057271c5d.Yk5VBWhfk5hRBcBxcC2ZrfOtrM-E1Fqgc9sRDwgpeNE
scenes-app-data-warehouse-sql-editor--bi-pivot-totals--dark:
- hash: v1.k794b7964.b5d8a1e1bb51f906561c748473e1154a390aaac2528c78c9aa52231fe731f450.t5sCvzOO_DUpmrH9_xzf7iaWx4XEVfQmYwWg99U7Ctk
+ hash: v1.k794b7964.ba7dd8440b82298b8a835b074caaa583b9891daedebbab72e63d46ca071296fd.rpuG6tkNxpKPeqhG9OfyGm5zmAbxX8n6050enO2w0k8
scenes-app-data-warehouse-sql-editor--bi-pivot-totals--light:
- hash: v1.k794b7964.cc07ceb5b769532f3d5308b04b517117ccca28af33bacf5099c408d878c7d975.p4TeTt9FkKRTBK9GRmMWC_I9JUHAnLVr0r0o9SlG77c
+ hash: v1.k794b7964.21c60f1857e95b0c1c69838d2e9cfd89172a39a73190680e20242082f8f4e418.gJ_J-XhbGJW54fGkLwYsvUlNjukbVkSo38aToib-iC0
scenes-app-data-warehouse-sql-editor--bi-quick-filters--dark:
- hash: v1.k794b7964.35e0d26ddb61c938132c00f550654180f9d66c7e6455cb12de6ce6ff553149d1.JdzMNnT9WMC96ulinxtMP0iIresbveLSSXw4okvzvI8
+ hash: v1.k794b7964.891179a5c3b2812c50491fee62425f1ece998d04e6e07cf3193dc3f8f0225c04.wGgdjGeHK86dTMz-KhnC1Yu8SLgTMLOtHH2uopiDNV8
scenes-app-data-warehouse-sql-editor--bi-quick-filters--light:
- hash: v1.k794b7964.dddc2df920032cab6abdb3bbb4aef0b6b13b35f02ddd5175d5caa27598f70ae4.ygQ4_htltBtYmRMCT11MV4kn6B8-gnnRzxqgNr8q-ew
+ hash: v1.k794b7964.6dc50c0ffe71227b8bc73fb2803d8f71a7e194ce75c0e0b3cb2ef6250c9bff45.eZQCYcqOtICgnZDi4EA8eLvQH3KrWO7cNT-ySses3C0
scenes-app-data-warehouse-sql-editor--bi-quick-filters-narrow--dark:
- hash: v1.k794b7964.9590f61c158e618f53c3dc02d81ec8bef1e3b2aa3174b8a508753d70fb887bce.DFSx0W35zC94NC4jIuTaEaZKVAw3nQEyBfVGv9QbGOs
+ hash: v1.k794b7964.45cb34e1887e2ef904eda3659590e0a0ff2779cbdc79ce1660527746043cd776.as-M5pRkI-EQcNTHXhRpozCY5q8FYhkyV34K8OgivYY
scenes-app-data-warehouse-sql-editor--bi-quick-filters-narrow--light:
- hash: v1.k794b7964.269778fa1ecd6129869d4386ba170f0ef864a465a38869a08167aa33823b2bb2.kURs3yUf_yw4EpuyE584CyppEsK-yvo0nqxtK_BlzDE
+ hash: v1.k794b7964.ad38cf101821f04b7a4c54859b79f9267eec63f988405cb7d8b3cc4ce06fafe7.10gV65jLd9_8rrrmJmAxweXy-4Sy7ayKJhWCUlDDy7Q
scenes-app-data-warehouse-sql-editor--bi-saved-insight--dark:
hash: v1.k794b7964.24b439b90164ae7db044155845ca7672d56a4cba3114d585495e5dda13f24767.wjZpVrMTZpKpD3Ih75kZd7Q0gbrlPNB-GP22OYGTzZE
scenes-app-data-warehouse-sql-editor--bi-saved-insight--light:
hash: v1.k794b7964.a81476825e10522264b1bc91fdd971de2742ac5a58336132a16c5783d3341fb1.7U0EUeE-WqdHuHI4EedMwFE35R94newfE_FFgsD3Do4
scenes-app-data-warehouse-sql-editor--bi-table-analysis--dark:
- hash: v1.k794b7964.49f5669675851052d30b2593306b0c3daa4b91c4d7132bb399a41aeb42369a38.5bbHWSZ3xiH0DyKrViYMZnUVGKyKyJEpMMFhixZFe88
+ hash: v1.k794b7964.467d3be4d930d429885a56a1a6fb3f5499306bdd20f183b0e295a68a4a8ec9e3.ovgkf--OxmJTB6ZJgX87yaL3JsNgfs6hSX_rEcu3838
scenes-app-data-warehouse-sql-editor--bi-table-analysis--light:
- hash: v1.k794b7964.e2ec7aa57a315f6031b34577a2b91eed39577a1b433a5dae7c0680bb1ea664ef.lIPQ12OAA_CzHjaNfMPn_L23loJ9zDE0y9ihzu4e9WE
+ hash: v1.k794b7964.614d75dcf1a8eb88a89855d533a073166e0ca184c0364d703f157de14a457f30.Yhom8F1BQD4NGDykAPbOK-Ycn5SLeeWrDRSd66S0nR4
scenes-app-data-warehouse-sql-editor--edited-insight--dark:
hash: v1.k794b7964.334b216a8359c768613cdec5b99a8a8ee26b6b5fac76397eaed8d6d1401a23c0.0pI7NMTufzUIfDel9Ngmhv3P3sdBu6IgpSj5xYNmYrY
scenes-app-data-warehouse-sql-editor--edited-insight--light:
@@ -10885,7 +10901,7 @@ snapshots:
scenes-app-inbox-scene--legacy--dark:
hash: v1.k794b7964.cf7ea7c47bba3a13402d4ffca0936c08040dee5c57ddf01bf8cee89892eb2664.dShBZ3vzzVmp5DadPnsR_vMHw11m5cA6LVA9A2eFOzE
scenes-app-inbox-scene--legacy--light:
- hash: v1.k794b7964.f503449990502057e4a2bf6d41dd2c94efad321503856eb11d338084507ed4fb.USiZ5UnWiaNkNJ1ci9aMi6h82TyPLJ1ASTwGfBmidj4
+ hash: v1.k794b7964.4dd5f54403e4b5baac2e7a5e92db534352dd9f65b754812575dc998efeb7d0af.u2XFY-8NWE4llhcIUEumJtEg14luO7tvzT7WAEiakvY
scenes-app-inbox-scene--legacy-report--dark:
hash: v1.k794b7964.73179e203433187821ff41208f41221b082f1ca19865fb7b26a751cffffdb633.cNaIyo_D196C9nTyUTVcxfSgwTM5ku-1KroxfCH34_s
scenes-app-inbox-scene--legacy-report--light:
diff --git a/frontend/src/lib/lemon-ui/LemonTable/LemonTable.tsx b/frontend/src/lib/lemon-ui/LemonTable/LemonTable.tsx
index bae048dacee3..9a0720d2cf71 100644
--- a/frontend/src/lib/lemon-ui/LemonTable/LemonTable.tsx
+++ b/frontend/src/lib/lemon-ui/LemonTable/LemonTable.tsx
@@ -84,6 +84,8 @@ export interface LemonTableProps<T extends Record<string, any>, K extends BulkSe
expandable?: ExpandableConfig<T>
/** Whether the header should be shown. The default value is `true`. */
showHeader?: boolean
+ /** Extra grouped header levels above the column titles, for hierarchical tables. */
+ headerRows?: { title: React.ReactNode; colSpan: number }[][]
/** Whether header titles should be uppercased. The default value is `true`. */
uppercaseHeader?: boolean
/**
@@ -169,6 +171,7 @@ export function LemonTable<T extends Record<string, any>, K extends BulkSelectio
scrollToTopOnPageChange = true,
expandable,
showHeader = true,
+ headerRows,
uppercaseHeader = true,
tableLayout = 'auto',
noSortingCancellation: disableSortingCancellation = false,
@@ -498,6 +501,21 @@ export function LemonTable<T extends Record<string, any>, K extends BulkSelectio
</colgroup>
{showHeader && (
<thead>
+ {headerRows?.map((row, rowIndex) => (
+ <tr key={rowIndex} className="LemonTable__row--grouping">
+ {isRowExpansionToggleShown && <th className="LemonTable__toggle" />}
+ {row.map((cell, cellIndex) => (
+ <th
+ key={cellIndex}
+ colSpan={cell.colSpan}
+ scope="colgroup"
+ className="LemonTable__boundary"
+ >
+ {cell.title}
+ </th>
+ ))}
+ </tr>
+ ))}
{columnGroups.some((group) => group.title) && (
<tr className="LemonTable__row--grouping">
{
diff --git a/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx b/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx
index 0d00f9829e55..d5fec248020d 100644
--- a/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx
@@ -29,9 +29,11 @@ import { shouldQueryBeAsync } from '~/queries/utils'
import { ChartDisplayType, ExportContext, ExporterFormat, InsightLogicProps } from '~/types'
import { alertsToThresholdGoalLines, insightAlertsLogic } from 'products/alerts/frontend/logic/insightAlertsLogic'
+import { BIComparisonSummary } from 'products/business_intelligence/frontend/BIComparisonSummary'
import { getBIChartRecord } from 'products/business_intelligence/frontend/biDrilldown'
import { biDrilldownLogic } from 'products/business_intelligence/frontend/biDrilldownLogic'
import { BIDrilldownModal } from 'products/business_intelligence/frontend/BIDrilldownModal'
+import { BIPivotTable } from 'products/business_intelligence/frontend/BIPivotTable'
import { getBIVisualizationSource } from 'products/business_intelligence/frontend/biQueryResults'
import { HogQLBoldNumber } from 'products/product_analytics/frontend/insights/shared/BoldNumber/BoldNumber'
@@ -274,6 +276,30 @@ function InternalDataTableVisualization(props: DataTableVisualizationProps): JSX
<StatelessInsightLoadingState queryId={queryId} pollResponse={pollResponse} />
</div>
)
+ } else if (
+ query.kind === NodeKind.BIVisualizationNode &&
+ (query.config.chartType === ChartDisplayType.TwoDimensionalHeatmap ||
+ (query.config.compareFilter?.compare &&
+ [ChartDisplayType.ActionsTable, ChartDisplayType.BoldNumber, ChartDisplayType.Metric].includes(
+ effectiveVisualizationType
+ )))
+ ) {
+ const resultProps = {
+ config: query.config,
+ columns: columns.map((column) => column.name),
+ results: 'results' in response && Array.isArray(response.results) ? response.results : [],
+ chartSettings,
+ onInspect: canDrill ? inspect : undefined,
+ }
+ component =
+ query.config.chartType === ChartDisplayType.TwoDimensionalHeatmap ? (
+ <BIPivotTable {...resultProps} />
+ ) : (
+ <BIComparisonSummary
+ {...resultProps}
+ card={effectiveVisualizationType !== ChartDisplayType.ActionsTable}
+ />
+ )
} else if (effectiveVisualizationType === ChartDisplayType.ActionsTable) {
component = (
<Table
@@ -392,8 +418,10 @@ function InternalDataTableVisualization(props: DataTableVisualizationProps): JSX
) : null}
{!responseLoading && response && 'hasMore' in response && response.hasMore ? (
<LemonBanner type="info">
- This worksheet reached its {query.config.limit.toLocaleString()} row limit. Increase the limit
- or narrow the filters to see all results.
+ {query.config.compareFilter?.compare
+ ? `This worksheet reached its ${(query.config.limit / 2).toLocaleString()} comparison group limit. Space is reserved for both periods within the ${query.config.limit.toLocaleString()} row limit.`
+ : `This worksheet reached its ${query.config.limit.toLocaleString()} row limit.`}{' '}
+ Increase the limit or narrow the filters to see all results.
</LemonBanner>
) : null}
{component}
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 3e3a661b3ae8..a5e395c61ac5 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -6205,6 +6205,11 @@
"limit": {
"$ref": "#/definitions/BIQueryLimit"
},
+ "missingDates": {
+ "description": "Fill missing date buckets before table calculations. Unset preserves observed points only.",
+ "enum": ["gap", "zero"],
+ "type": "string"
+ },
"resultFilterGroup": {
"$ref": "#/definitions/BIConditionGroup"
},
@@ -6414,6 +6419,10 @@
"description": "Dimension ID to traverse. Unset chooses the date dimension; 'table' traverses all dimensions.",
"type": "string"
},
+ "requireFullWindow": {
+ "description": "Require a complete window of non-null values before displaying a moving average.",
+ "type": "boolean"
+ },
"type": {
"$ref": "#/definitions/BITableCalculationType"
},
diff --git a/frontend/src/queries/schema/schema-business-intelligence.ts b/frontend/src/queries/schema/schema-business-intelligence.ts
index 5d0b14ffa2d7..bad63be64787 100644
--- a/frontend/src/queries/schema/schema-business-intelligence.ts
+++ b/frontend/src/queries/schema/schema-business-intelligence.ts
@@ -88,6 +88,8 @@ export interface BITableCalculation {
computeUsing?: string
/** Number of points, including the current point, in a trailing moving average. */
window?: positive_integer
+ /** Require a complete window of non-null values before displaying a moving average. */
+ requireFullWindow?: boolean
}
export interface BITopN {
@@ -132,6 +134,8 @@ export interface BIConfig {
sort?: BISort | null
topN?: BITopN
totals?: BITotals
+ /** Fill missing date buckets before table calculations. Unset preserves observed points only. */
+ missingDates?: 'gap' | 'zero'
}
export interface BIConditionGroup {
diff --git a/posthog/hogql/filters.py b/posthog/hogql/filters.py
index e57c84f525ae..b6fb6f0bf0a3 100644
--- a/posthog/hogql/filters.py
+++ b/posthog/hogql/filters.py
@@ -263,36 +263,15 @@ class ReplaceFilters(CloningVisitor):
if node.chain == ["filters"]:
return self._replace_native_filters()
- if node.chain == ["filters", "dateRange", "from"]:
- compare_op_wrapper = self.compare_operations[-1]
-
- if no_filters:
- compare_op_wrapper.skip = True
- return ast.Constant(value=True)
-
- assert self.filters is not None
-
- date_from = self._resolve_date_from()
- if date_from is not None:
- return ast.Constant(value=date_from)
- else:
- compare_op_wrapper.skip = True
- return ast.Constant(value=True)
- if node.chain == ["filters", "dateRange", "to"]:
- compare_op_wrapper = self.compare_operations[-1]
-
- if no_filters:
- compare_op_wrapper.skip = True
- return ast.Constant(value=True)
-
- assert self.filters is not None
-
- date_to, _date_to_inclusive = self._resolve_date_to()
- if date_to is not None:
- return ast.Constant(value=date_to)
- else:
- compare_op_wrapper.skip = True
+ if node.chain in (["filters", "dateRange", "from"], ["filters", "dateRange", "to"]):
+ bound = node.chain[-1]
+ value = None if no_filters else self._resolve_date_from() if bound == "from" else self._resolve_date_to()[0]
+ if value is not None:
+ return ast.Constant(value=value)
+ if self.compare_operations:
+ self.compare_operations[-1].skip = True
return ast.Constant(value=True)
+ raise QueryError(f"Select a bounded date range to use {{filters.dateRange.{bound}}} as a value")
if node.chain == ["filters", "interval"]:
return self._replace_interval([])
diff --git a/posthog/hogql/test/test_filters.py b/posthog/hogql/test/test_filters.py
index ea7e72d081e2..4eaf179afe21 100644
--- a/posthog/hogql/test/test_filters.py
+++ b/posthog/hogql/test/test_filters.py
@@ -38,6 +38,55 @@ from products.cohorts.backend.models.cohort import Cohort
class TestFilters(BaseTest):
maxDiff = None
+ @parameterized.expand([("gap", False), ("zero", True)])
+ def test_fill_date_bounds_before_window_calculations(self, _name: str, zero: bool) -> None:
+ query = parse_select(
+ """
+ WITH observed AS (
+ SELECT toDateTime('2026-01-01') AS day, 'a' AS series, 10 AS amount
+ UNION ALL SELECT toDateTime('2026-01-03'), 'a', 30
+ UNION ALL SELECT toDateTime('2026-01-02'), 'b', 8
+ ), filled AS (
+ SELECT day, series, toNullable(toFloat(amount)) AS amount FROM observed
+ ORDER BY series, day WITH FILL
+ FROM toStartOfDay({filters.dateRange.from})
+ TO toStartOfDay({filters.dateRange.to}) + INTERVAL 1 DAY
+ STEP INTERVAL 1 DAY
+ )
+ SELECT series, toString(toDate(day)), amount,
+ avg(amount) OVER (PARTITION BY series ORDER BY day ROWS BETWEEN 2 PRECEDING AND CURRENT ROW),
+ if(count(amount) OVER (PARTITION BY series ORDER BY day ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) = 3,
+ avg(amount) OVER (PARTITION BY series ORDER BY day ROWS BETWEEN 2 PRECEDING AND CURRENT ROW), NULL)
+ FROM filled ORDER BY series, day
+ """
+ )
+ if zero:
+ assert isinstance(query, ast.SelectQuery)
+ assert query.ctes is not None
+ filled = query.ctes["filled"].expr
+ assert isinstance(filled, ast.SelectQuery)
+ filled.interpolate = [ast.InterpolateExpr(expr=ast.Field(chain=["amount"]), value=ast.Constant(value=0))]
+ query = replace_filters(
+ query,
+ HogQLFilters(dateRange=DateRange(date_from="2026-01-01", date_to="2026-01-03")),
+ self.team,
+ )
+ result = execute_hogql_query(query, team=self.team)
+ assert len(result.results) == 6
+ assert result.results[1][:3] == ("a", "2026-01-02", 0 if zero else None)
+ assert result.results[2][3] == (40 / 3 if zero else 20)
+ assert result.results[2][4] == (40 / 3 if zero else None)
+ assert result.results[4][3] == (4 if zero else 8)
+
+ @parameterized.expand(["from", "to"])
+ def test_date_bound_value_requires_filters(self, bound: str) -> None:
+ query = parse_select(
+ "SELECT {bound}",
+ placeholders={"bound": ast.Placeholder(expr=ast.Field(chain=["filters", "dateRange", bound]))},
+ )
+ with self.assertRaisesMessage(QueryError, "Select a"):
+ replace_filters(query, None, self.team)
+
def _parse_expr(self, expr: str, placeholders: Optional[dict[str, Any]] = None):
return clear_locations(parse_expr(expr, placeholders=placeholders))
diff --git a/posthog/schema.py b/posthog/schema.py
index 7d705863161b..962cebfa78df 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -210,6 +210,7 @@ from posthog.schema_enums import (
MetricsReducer as MetricsReducer,
MetricsStatSummary as MetricsStatSummary,
MetricSummary as MetricSummary,
+ MissingDates as MissingDates,
MultipleBreakdownType as MultipleBreakdownType,
MultipleVariantHandling as MultipleVariantHandling,
MultiQuestionFormFieldType as MultiQuestionFormFieldType,
@@ -5051,6 +5052,10 @@ class BITableCalculation(BaseModel):
default=None,
description=("Dimension ID to traverse. Unset chooses the date dimension; 'table' traverses all dimensions."),
)
+ requireFullWindow: bool | None = Field(
+ default=None,
+ description=("Require a complete window of non-null values before displaying a moving average."),
+ )
type: BITableCalculationType
window: conint(ge=1) | None = Field(
default=None,
@@ -11143,6 +11148,10 @@ class BIConfig(BaseModel):
dateRange: DateRange | None = None
filters: list[BIFilter]
limit: BIQueryLimit
+ missingDates: MissingDates | None = Field(
+ default=None,
+ description=("Fill missing date buckets before table calculations. Unset preserves observed points only."),
+ )
resultFilterGroup: BIConditionGroup | None = None
resultFilters: list[BIResultFilter] | None = None
rowFilterGroup: BIConditionGroup | None = None
diff --git a/posthog/schema_enums.py b/posthog/schema_enums.py
index 7d4d64da4a41..0b4578eb20a7 100644
--- a/posthog/schema_enums.py
+++ b/posthog/schema_enums.py
@@ -636,6 +636,11 @@ class Operator1(StrEnum):
OR_ = "OR"
+class MissingDates(StrEnum):
+ GAP = "gap"
+ ZERO = "zero"
+
+
class BIDateBucket(StrEnum):
MINUTE = "minute"
HOUR = "hour"
diff --git a/products/business_intelligence/frontend/BIAnalysisControls.tsx b/products/business_intelligence/frontend/BIAnalysisControls.tsx
index 97bfeb5e3971..415e867c4e46 100644
--- a/products/business_intelligence/frontend/BIAnalysisControls.tsx
+++ b/products/business_intelligence/frontend/BIAnalysisControls.tsx
@@ -6,16 +6,44 @@ import { ChartDisplayType } from '~/types'
import { biEditorLogic } from './biEditorLogic'
import { getBIValuePillLabel, isDateTimeBIField } from './biEditorTypes'
+import { getBIMissingDatesDisabledReason } from './biTimeSeries'
import { BIShelfCard } from './components/BIShelfCard'
export function BIAnalysisControls(): JSX.Element {
const { config } = useValues(biEditorLogic)
- const { setTopN, setTotals } = useActions(biEditorLogic)
+ const { setTopN, setTotals, setMissingDates } = useActions(biEditorLogic)
const dimensions = [...config.rows, ...config.columns].filter((field) => !isDateTimeBIField(field))
const table = [ChartDisplayType.ActionsTable, ChartDisplayType.TwoDimensionalHeatmap].includes(config.chartType)
return (
<BIShelfCard title="Analysis">
<div className="flex min-w-0 flex-col gap-2">
+ {[...config.rows, ...config.columns].some(isDateTimeBIField) ? (
+ <>
+ <LemonLabel>Missing dates</LemonLabel>
+ <LemonSelect
+ size="xsmall"
+ fullWidth
+ aria-label="Missing dates"
+ data-attr="bi-editor-missing-dates"
+ value={getBIMissingDatesDisabledReason(config) ? null : (config.missingDates ?? null)}
+ options={[
+ { value: null, label: 'Observed points only' },
+ {
+ value: 'gap',
+ label: 'Show gaps',
+ disabledReason: getBIMissingDatesDisabledReason(config),
+ },
+ {
+ value: 'zero',
+ label: 'Fill with zero',
+ disabledReason: getBIMissingDatesDisabledReason(config),
+ },
+ ]}
+ onChange={(value) => setMissingDates(value ?? undefined)}
+ />
+ <span className="text-xs text-secondary">Applied per series before table calculations.</span>
+ </>
+ ) : null}
<LemonCheckbox
labelClassName="text-xs"
label="Top N breakdown"
diff --git a/products/business_intelligence/frontend/BIComparisonSummary.stories.tsx b/products/business_intelligence/frontend/BIComparisonSummary.stories.tsx
new file mode 100644
index 000000000000..889a8685e5e2
--- /dev/null
+++ b/products/business_intelligence/frontend/BIComparisonSummary.stories.tsx
@@ -0,0 +1,90 @@
+import { Meta, StoryObj } from '@storybook/react'
+
+import { BIConfig, BIField } from '~/queries/schema/schema-business-intelligence'
+import { ChartDisplayType } from '~/types'
+
+import { BIComparisonSummary } from './BIComparisonSummary'
+import { DEFAULT_BI_CONFIG } from './biEditorTypes'
+
+const field: BIField = {
+ id: 'revenue',
+ name: 'revenue',
+ expression: 'revenue',
+ type: 'float',
+ source: { table: 'events' },
+}
+const config: BIConfig = {
+ ...DEFAULT_BI_CONFIG,
+ source: field.source,
+ chartType: ChartDisplayType.BoldNumber,
+ dateRange: { date_from: '-7d' },
+ compareFilter: { compare: true },
+ values: [
+ {
+ field,
+ aggregation: 'sum',
+ display: { label: 'Revenue' },
+ formatting: { style: 'number', prefix: '€', decimalPlaces: 2 },
+ },
+ ],
+}
+const meta: Meta<typeof BIComparisonSummary> = {
+ title: 'Products/Business intelligence/Comparison summary',
+ component: BIComparisonSummary,
+ parameters: { layout: 'fullscreen' },
+ decorators: [
+ (Story) => (
+ <div className="w-full max-w-5xl">
+ <Story />
+ </div>
+ ),
+ ],
+}
+export default meta
+export const KPI: StoryObj<typeof BIComparisonSummary> = {
+ args: {
+ config,
+ card: true,
+ columns: ['sum_revenue', 'bi_comparison'],
+ results: [
+ [12500, 'Current period'],
+ [10000, 'Previous period'],
+ ],
+ },
+}
+export const Table: StoryObj<typeof BIComparisonSummary> = {
+ args: {
+ config: {
+ ...config,
+ chartType: ChartDisplayType.ActionsTable,
+ rows: [{ ...field, id: 'event', expression: 'event', name: 'Event', type: 'string' }],
+ },
+ columns: ['bi_row_event', 'sum_revenue', 'bi_comparison'],
+ results: [
+ ['Purchase', 12500, 'Current period'],
+ ['Purchase', 10000, 'Previous period'],
+ ['New subscription', 500, 'Current period'],
+ ['New subscription', 0, 'Previous period'],
+ ['Refund', -100, 'Current period'],
+ ['Refund', -200, 'Previous period'],
+ ],
+ },
+}
+
+export const KPIWithBreakdowns: StoryObj<typeof BIComparisonSummary> = {
+ args: {
+ ...KPI.args,
+ config: {
+ ...config,
+ rows: [{ ...field, id: 'country', name: 'country', expression: 'country', type: 'string' }],
+ columns: [{ ...field, id: 'device', name: 'device', expression: 'device', type: 'string' }],
+ },
+ columns: ['bi_row_country', 'bi_column_device', 'sum_revenue', 'bi_comparison'],
+ results: [
+ ['France', 'Mobile', 12500, 'Current period'],
+ ['France', 'Mobile', 10000, 'Previous period'],
+ ['Germany', 'Desktop', 3500, 'Current period'],
+ ['Germany', 'Desktop', 4000, 'Previous period'],
+ ],
+ },
+}
diff --git a/products/business_intelligence/frontend/BIComparisonSummary.tsx b/products/business_intelligence/frontend/BIComparisonSummary.tsx
new file mode 100644
index 000000000000..c759fb730111
--- /dev/null
+++ b/products/business_intelligence/frontend/BIComparisonSummary.tsx
@@ -0,0 +1,137 @@
+import { LemonButton, LemonTable } from '@posthog/lemon-ui'
+
+import { BIConfig } from '~/queries/schema/schema-business-intelligence'
+import { ChartSettings } from '~/queries/schema/schema-general'
+
+import { BIComparisonRow, buildBIComparisonRows, getBIComparisonValues } from './biComparisonResults'
+import { formatBIMeasure, getBIResultMeasures } from './biResultPresentation'
+
+export function BIComparisonSummary({
+ config,
+ columns,
+ results,
+ chartSettings,
+ card = false,
+ onInspect,
+}: {
+ config: BIConfig
+ columns: string[]
+ results: unknown[][]
+ chartSettings?: ChartSettings
+ card?: boolean
+ onInspect?: (record: Record<string, unknown>) => void
+}): JSX.Element {
+ const rows = buildBIComparisonRows(config, columns, results)
+ const measures = getBIResultMeasures(config, chartSettings)
+ const dimensions = [...config.rows, ...config.columns]
+ const summaries = [
+ { key: 'current' as const, label: 'Current' },
+ { key: 'previous' as const, label: config.compareFilter?.compare_to ? 'Comparison' : 'Previous' },
+ { key: 'change' as const, label: 'Absolute change' },
+ { key: 'percent' as const, label: '% change' },
+ ]
+ const cell = (
+ row: BIComparisonRow,
+ measure: (typeof measures)[number],
+ key: (typeof summaries)[number]['key']
+ ): JSX.Element => {
+ const values = getBIComparisonValues(row, measure.column)
+ const label = formatBIMeasure(
+ values[key],
+ key === 'percent' ? { formatting: { style: 'percent', decimalPlaces: 1 } } : measure.settings
+ )
+ const record = key === 'current' ? row.current : key === 'previous' ? row.previous : undefined
+ return record && onInspect ? (
+ <LemonButton
+ size="xsmall"
+ noPadding={card}
+ type="tertiary"
+ className="justify-end !text-inherit"
+ data-attr="bi-comparison-inspect"
+ onClick={() => onInspect(record)}
+ tooltip="Explore this period"
+ >
+ <span className={card ? (key === 'current' ? 'text-3xl font-semibold' : 'text-xl') : undefined}>
+ {label}
+ </span>
+ </LemonButton>
+ ) : (
+ <span
+ title={
+ key === 'percent' && values.previous === 0
+ ? 'Percentage change is undefined when the previous value is zero'
+ : undefined
+ }
+ >
+ {label}
+ </span>
+ )
+ }
+ if (card) {
+ return (
+ <div className="flex flex-col gap-4 p-4 w-full min-w-0" data-attr="bi-comparison-kpi">
+ {(rows.length ? rows : [{ key: 'empty', dimensions: [] }]).flatMap((row) =>
+ measures.map((measure) => (
+ <div key={`${row.key}:${measure.column}`} className="flex flex-col gap-2">
+ {row.dimensions.length > 0 && (
+ <div className="text-xs text-secondary break-words">
+ {row.dimensions
+ .map(
+ (value, index) => `${dimensions[index].name}: ${String(value ?? '(empty)')}`
+ )
+ .join(' · ')}
+ </div>
+ )}
+ <div className="text-sm font-medium">{measure.label}</div>
+ <div className="flex flex-wrap gap-x-8 gap-y-4">
+ {summaries.map(({ key, label }) => (
+ <div key={key} className="min-w-0 flex flex-col gap-1">
+ <span className="text-xs text-secondary">{label}</span>
+ <span className={key === 'current' ? 'text-3xl font-semibold' : 'text-xl'}>
+ {cell(row, measure, key)}
+ </span>
+ </div>
+ ))}
+ </div>
+ </div>
+ ))
+ )}
+ </div>
+ )
+ }
+ return (
+ <div className="p-2 w-full min-w-0" data-attr="bi-comparison-table">
+ <LemonTable<BIComparisonRow>
+ dataSource={rows}
+ rowKey="key"
+ size="small"
+ uppercaseHeader={false}
+ useURLForSorting={false}
+ emptyState="No results for these periods"
+ columns={[
+ ...(dimensions.length
+ ? [
+ {
+ children: dimensions.map((field, index) => ({
+ key: field.id,
+ title: field.name,
+ render: (_: unknown, row: BIComparisonRow) =>
+ String(row.dimensions[index] ?? '(empty)'),
+ })),
+ },
+ ]
+ : []),
+ ...measures.map((measure) => ({
+ title: measure.label,
+ children: summaries.map(({ key, label }) => ({
+ key: `${measure.column}:${key}`,
+ title: label,
+ align: 'right' as const,
+ render: (_: unknown, row: BIComparisonRow) => cell(row, measure, key),
+ })),
+ })),
+ ]}
+ />
+ </div>
+ )
+}
diff --git a/products/business_intelligence/frontend/BIMeasureAnalysis.tsx b/products/business_intelligence/frontend/BIMeasureAnalysis.tsx
index 0cd212c8cf32..932164334425 100644
--- a/products/business_intelligence/frontend/BIMeasureAnalysis.tsx
+++ b/products/business_intelligence/frontend/BIMeasureAnalysis.tsx
@@ -1,16 +1,18 @@
import { useActions, useValues } from 'kea'
-import { LemonButton, LemonInput, LemonLabel, LemonSelect } from '@posthog/lemon-ui'
+import { LemonButton, LemonCheckbox, LemonInput, LemonLabel, LemonSelect } from '@posthog/lemon-ui'
import { BI_TABLE_CALCULATIONS } from './biAnalysis'
import { biEditorLogic } from './biEditorLogic'
import { getBIValuePillLabel } from './biEditorTypes'
+import { getBIMissingDatesDisabledReason } from './biTimeSeries'
export function BIMeasureAnalysis({ index }: { index: number }): JSX.Element {
const { config } = useValues(biEditorLogic)
const { setTableCalculation, editMeasureSettings } = useActions(biEditorLogic)
const value = config.values[index]
const calculation = value.tableCalculation
+ const missingDates = getBIMissingDatesDisabledReason(config) ? undefined : config.missingDates
return (
<div className="flex min-w-0 flex-col gap-1 border-t pt-2">
<LemonLabel className="truncate">{getBIValuePillLabel(value)}</LemonLabel>
@@ -51,24 +53,49 @@ export function BIMeasureAnalysis({ index }: { index: number }): JSX.Element {
}
/>
{calculation.type === 'moving_average' ? (
- <LemonInput
- type="number"
- size="small"
- min={1}
- max={1000}
- value={calculation.window ?? 3}
- aria-label="Moving average points"
- suffix={<span>points</span>}
- onChange={(window) =>
- setTableCalculation(index, {
- ...calculation,
- window: Math.max(1, Math.min(1000, Math.trunc(window ?? 3))),
- })
- }
- />
+ <>
+ <LemonInput
+ type="number"
+ size="small"
+ min={1}
+ max={1000}
+ value={calculation.window ?? 3}
+ aria-label="Moving average points"
+ suffix={<span>points</span>}
+ onChange={(window) =>
+ setTableCalculation(index, {
+ ...calculation,
+ window: Math.max(1, Math.min(1000, Math.trunc(window ?? 3))),
+ })
+ }
+ />
+ <LemonCheckbox
+ label="Require a full window"
+ labelClassName="text-xs"
+ data-attr="bi-editor-moving-average-full-window"
+ checked={!!calculation.requireFullWindow}
+ onChange={(requireFullWindow) =>
+ setTableCalculation(index, { ...calculation, requireFullWindow })
+ }
+ />
+ <span className="text-xs text-secondary">
+ Trailing {calculation.window ?? 3} points, including the current point.
+ {calculation.computeUsing === 'table'
+ ? ' Traverses the entire table.'
+ : ' Other dimensions define separate series.'}
+ {calculation.requireFullWindow
+ ? ' Blank until every point in the window has a value.'
+ : ' Partial windows use the available values; gaps are excluded from the average.'}
+ </span>
+ </>
) : null}
<span className="text-xs text-secondary">
- Ascending order within each series. Missing points stay missing.
+ Ascending order.{' '}
+ {missingDates === 'zero'
+ ? 'Empty date buckets contribute zero.'
+ : missingDates === 'gap'
+ ? 'Empty date buckets occupy a point in the window.'
+ : 'Only observed points occupy a point in the window.'}
</span>
</>
) : null}
diff --git a/products/business_intelligence/frontend/BIPivotTable.stories.tsx b/products/business_intelligence/frontend/BIPivotTable.stories.tsx
new file mode 100644
index 000000000000..ffd2bad626e3
--- /dev/null
+++ b/products/business_intelligence/frontend/BIPivotTable.stories.tsx
@@ -0,0 +1,89 @@
+import { Meta, StoryObj } from '@storybook/react'
+
+import { BIConfig, BIField } from '~/queries/schema/schema-business-intelligence'
+import { ChartDisplayType } from '~/types'
+
+import { DEFAULT_BI_CONFIG } from './biEditorTypes'
+import { BIPivotTable } from './BIPivotTable'
+
+const field = (name: string): BIField => ({
+ id: name,
+ name,
+ expression: name,
+ type: 'string',
+ source: { table: 'events' },
+})
+const config: BIConfig = {
+ ...DEFAULT_BI_CONFIG,
+ source: { table: 'events' },
+ chartType: ChartDisplayType.TwoDimensionalHeatmap,
+ rows: [field('Region'), field('City')],
+ columns: [field('Year'), field('Quarter')],
+ values: [
+ {
+ field: field('revenue'),
+ aggregation: 'sum',
+ formatting: { style: 'number', prefix: '€', decimalPlaces: 0 },
+ display: { label: 'Revenue' },
+ },
+ {
+ field: field('user'),
+ aggregation: 'count_distinct',
+ display: { label: 'Customers' },
+ formatting: { style: 'number', decimalPlaces: 0 },
+ },
+ ],
+ totals: { rows: true, columns: true, subtotals: true },
+}
+const detail: [string, string, string, number, number][] = [
+ ['Europe', 'Paris', 'Q1', 1200, 18],
+ ['Europe', 'Paris', 'Q2', 1500, 23],
+ ['Europe', 'Rome', 'Q1', 800, 12],
+ ['Europe', 'Rome', 'Q2', 950, 14],
+ ['Americas', 'Boston', 'Q1', 2100, 31],
+ ['Americas', 'Boston', 'Q2', 2400, 34],
+]
+const results = [
+ ['Europe', 'Paris'],
+ ['Europe', 'Rome'],
+ ['Europe', 'Total'],
+ ['Americas', 'Boston'],
+ ['Americas', 'Total'],
+ ['Total', 'Total'],
+].flatMap((row) =>
+ [
+ ['2026', 'Q1'],
+ ['2026', 'Q2'],
+ ['2026', 'Total'],
+ ['Total', 'Total'],
+ ].map((column) => {
+ const matching = detail.filter(
+ ([region, city, quarter]) =>
+ (row[0] === 'Total' || region === row[0]) &&
+ (row[1] === 'Total' || city === row[1]) &&
+ (column[1] === 'Total' || quarter === column[1])
+ )
+ return [
+ JSON.stringify(row),
+ JSON.stringify(column),
+ matching.reduce((sum, item) => sum + item[3], 0),
+ matching.reduce((sum, item) => sum + item[4], 0),
+ ]
+ })
+)
+
+const meta: Meta<typeof BIPivotTable> = {
+ title: 'Products/Business intelligence/Pivot table',
+ component: BIPivotTable,
+ parameters: { layout: 'fullscreen' },
+ args: { config, columns: ['bi_rows', 'bi_columns', 'sum_revenue', 'count_distinct_user_2'], results },
+ decorators: [
+ (Story) => (
+ <div className="w-full max-w-5xl">
+ <Story />
+ </div>
+ ),
+ ],
+}
+export default meta
+export const MultipleMeasuresAndHierarchies: StoryObj<typeof BIPivotTable> = {}
diff --git a/products/business_intelligence/frontend/BIPivotTable.tsx b/products/business_intelligence/frontend/BIPivotTable.tsx
new file mode 100644
index 000000000000..5765692ec93a
--- /dev/null
+++ b/products/business_intelligence/frontend/BIPivotTable.tsx
@@ -0,0 +1,171 @@
+import { useMemo, useState } from 'react'
+
+import { IconChevronDown, IconChevronRight } from '@posthog/icons'
+import { LemonBanner, LemonButton, LemonTable } from '@posthog/lemon-ui'
+
+import { BIConfig } from '~/queries/schema/schema-business-intelligence'
+import { ChartSettings } from '~/queries/schema/schema-general'
+
+import { captureBIWorksheetAction } from './biEditorAnalytics'
+import { biPivotCellKey, biPivotKey, BIPivotMember, buildBIPivotModel, visibleBIPivotMembers } from './biPivot'
+import { formatBIMeasure, getBIResultMeasures } from './biResultPresentation'
+
+export function BIPivotTable({
+ config,
+ columns,
+ results,
+ chartSettings,
+ onInspect,
+}: {
+ config: BIConfig
+ columns: string[]
+ results: unknown[][]
+ chartSettings?: ChartSettings
+ onInspect?: (record: Record<string, unknown>) => void
+}): JSX.Element {
+ const [collapsedRows, setCollapsedRows] = useState<Set<string>>(new Set())
+ const [collapsedColumns, setCollapsedColumns] = useState<Set<string>>(new Set())
+ const model = useMemo(() => buildBIPivotModel(config, columns, results), [config, columns, results])
+ const measures = getBIResultMeasures(config, chartSettings)
+ const rows = visibleBIPivotMembers(model.rows, collapsedRows, true)
+ const visibleColumns = visibleBIPivotMembers(model.columns, collapsedColumns, !!config.totals?.subtotals)
+ if (
+ rows.length * visibleColumns.length * measures.length > 50000 ||
+ visibleColumns.length * measures.length > 500
+ ) {
+ return (
+ <LemonBanner type="info">Too many pivot cells to display. Reduce the dimensions or use Top N.</LemonBanner>
+ )
+ }
+ const toggle = (member: BIPivotMember, side: 'rows' | 'columns'): void => {
+ const setter = side === 'rows' ? setCollapsedRows : setCollapsedColumns
+ setter((current) => {
+ const next = new Set(current)
+ next.has(member.key) ? next.delete(member.key) : next.add(member.key)
+ return next
+ })
+ captureBIWorksheetAction('pivot_hierarchy_toggled', config, {
+ hierarchy_axis: side,
+ hierarchy_depth: member.path.length,
+ expanded: (side === 'rows' ? collapsedRows : collapsedColumns).has(member.key),
+ })
+ }
+ const header = (member: BIPivotMember, side: 'rows' | 'columns'): JSX.Element => {
+ const collapsed = (side === 'rows' ? collapsedRows : collapsedColumns).has(member.key)
+ return member.children.length ? (
+ <LemonButton
+ size="xsmall"
+ type="tertiary"
+ icon={collapsed ? <IconChevronRight /> : <IconChevronDown />}
+ aria-expanded={!collapsed}
+ aria-label={`${collapsed ? 'Expand' : 'Collapse'} ${member.label}`}
+ data-attr={`bi-pivot-toggle-${side}`}
+ onClick={() => toggle(member, side)}
+ >
+ {member.label}
+ </LemonButton>
+ ) : (
+ <span>{member.label}</span>
+ )
+ }
+ const findMember = (path: unknown[]): BIPivotMember | undefined => {
+ let siblings = model.columns
+ let member: BIPivotMember | undefined
+ for (let depth = 1; depth <= path.length; depth++) {
+ member = siblings.find((item) => item.key === biPivotKey(path.slice(0, depth)))
+ siblings = member?.children ?? []
+ }
+ return member
+ }
+ const headerRows = Array.from({ length: config.columns.length }, (_, depth) => {
+ const cells: { title: React.ReactNode; colSpan: number; key: string }[] = [
+ {
+ title: depth === 0 ? config.columns.map((field) => field.name).join(' / ') : '',
+ colSpan: 1,
+ key: 'rows',
+ },
+ ]
+ for (const column of visibleColumns) {
+ const path = column.path.slice(0, depth + 1)
+ const key = biPivotKey(path)
+ const previous = cells[cells.length - 1]
+ if (previous.key === key) {
+ previous.colSpan += measures.length
+ } else {
+ const member = findMember(path)
+ cells.push({
+ key,
+ colSpan: measures.length,
+ title:
+ depth < column.path.length && member
+ ? header(member, 'columns')
+ : depth === 0 && !column.path.length
+ ? 'Total'
+ : depth === column.path.length && column.children.length
+ ? 'Subtotal'
+ : '',
+ })
+ }
+ }
+ return cells
+ })
+ return (
+ <div className="p-2 w-full min-w-0" data-attr="bi-pivot-table">
+ <LemonTable<BIPivotMember>
+ size="small"
+ rowKey="key"
+ dataSource={rows}
+ useURLForSorting={false}
+ firstColumnSticky
+ uppercaseHeader={false}
+ headerRows={headerRows}
+ emptyState="No results for these filters"
+ columns={[
+ {
+ key: 'rows',
+ title: config.rows.map((field) => field.name).join(' / '),
+ render: (_, member) => (
+ <div className="flex items-center gap-1 whitespace-nowrap">
+ {member.path.slice(1).map((_, index) => (
+ <span key={index} className="w-3 shrink-0" />
+ ))}
+ {header(member, 'rows')}
+ </div>
+ ),
+ },
+ ...visibleColumns.flatMap((column) =>
+ measures.map((measure) => ({
+ key: `${column.key}:${measure.column}`,
+ title: measure.label,
+ align: 'right' as const,
+ render: (_: unknown, row: BIPivotMember) => {
+ const record = model.cells.get(biPivotCellKey(row.path, column.path))
+ const showValue =
+ !row.children.length || collapsedRows.has(row.key) || config.totals?.subtotals
+ const label = formatBIMeasure(
+ showValue ? record?.[measure.column] : null,
+ measure.settings
+ )
+ return record && showValue && onInspect ? (
+ <LemonButton
+ size="xsmall"
+ type="tertiary"
+ fullWidth
+ className="justify-end"
+ data-attr="bi-pivot-inspect"
+ onClick={() => onInspect(record)}
+ tooltip="Explore this result"
+ >
+ {label}
+ </LemonButton>
+ ) : (
+ label
+ )
+ },
+ }))
+ ),
+ ]}
+ />
+ </div>
+ )
+}
diff --git a/products/business_intelligence/frontend/biAnalysis.test.ts b/products/business_intelligence/frontend/biAnalysis.test.ts
index 3ca1e259c5c1..7cf2765da423 100644
--- a/products/business_intelligence/frontend/biAnalysis.test.ts
+++ b/products/business_intelligence/frontend/biAnalysis.test.ts
@@ -20,6 +20,36 @@ const config: BIConfig = {
}
describe('BI analysis queries', () => {
+ it.each(['gap', 'zero'] as const)(
+ 'fills %s date buckets separately in each period before window calculations',
+ (missingDates) => {
+ const worksheet: BIConfig = {
+ ...config,
+ chartType: ChartDisplayType.ActionsLineGraph,
+ missingDates,
+ dateRange: { date_from: '-7d' },
+ compareFilter: { compare: true },
+ values: [
+ {
+ ...config.values[0],
+ tableCalculation: { type: 'moving_average', window: 3, requireFullWindow: true },
+ },
+ ],
+ }
+ const parsed = parseBIEditorState(BIEditorView.BI, worksheet)!.config
+ expect(parsed.missingDates).toBe(missingDates)
+ expect(parsed.values[0].tableCalculation?.requireFullWindow).toBe(true)
+ const query = buildBIQuery(parsed)!.query
+ expect(query).toContain('bi_current_filled AS')
+ expect(query).toContain('bi_previous_filled AS')
+ expect(query).toContain('FROM toStartOfDay({filters.dateRange.from})')
+ expect(query).toContain('ORDER BY bi_column_event ASC, bi_row_timestamp ASC WITH FILL')
+ expect(query).toContain('2 PRECEDING AND CURRENT ROW) = 3')
+ expect(query.indexOf('bi_current_filled AS')).toBeLessThan(query.indexOf('bi_calculated AS'))
+ expect(query.includes('INTERPOLATE (sum_properties_amount AS 0)')).toBe(missingDates === 'zero')
+ expect(buildBIQuery({ ...worksheet, dateRange: { date_from: 'all' } })!.query).not.toContain('WITH FILL')
+ }
+ )
it.each([false, true])(
'filters aggregated and calculated results before the final limit (comparison: %s)',
(compare) => {
@@ -143,7 +173,10 @@ describe('BI analysis queries', () => {
expect(result.query).toContain("['1', 'Other']")
expect(result.query).toContain("' (category)'")
expect(result.query).not.toMatch(/sum\((average|count_distinct)/)
- expect(result.query).toContain('grouping(bi_row_timestamp, bi_column_event)')
+ expect(result.query).toContain('grouping(toStartOfDay(timestamp), if((event IN (SELECT bi_key FROM bi_top)')
+ expect(buildBIQuery({ ...worksheet, topN: undefined, totals: undefined })!.query).toContain(
+ "startsWith(toString(bi_column_event), 'Total')"
+ )
expect(parseBIEditorState(BIEditorView.BI, worksheet)?.config.topN).toEqual(worksheet.topN)
expect(parseBIEditorState(BIEditorView.BI, worksheet)?.config.totals).toEqual(worksheet.totals)
})
@@ -169,7 +202,7 @@ describe('BI analysis queries', () => {
expect(probe.query).toMatch(/LIMIT 101$/)
})
- it('probes beyond the combined comparison limit without changing the saved query', () => {
+ it('limits complete comparison groups and probes one extra group without changing the saved query', () => {
const worksheet: BIConfig = {
...config,
limit: 100,
@@ -178,11 +211,12 @@ describe('BI analysis queries', () => {
}
const saved = buildBIQuery(worksheet)!
const probe = buildBIQuery(worksheet, true)!
- expect(saved.query).toMatch(/^SELECT \* FROM \(/)
- expect(saved.query).toMatch(/\)\) LIMIT 100$/)
+ expect(saved.query).toContain('bi_comparison_rank <= 50')
+ expect(saved.query).toMatch(/LIMIT 100$/)
expect(probe.query).toContain('UNION ALL')
- expect(probe.query.match(/LIMIT 101/g)).toHaveLength(3)
- expect(probe.query).toMatch(/\)\) LIMIT 101$/)
+ expect(probe.query.match(/LIMIT /g)).toHaveLength(1)
+ expect(probe.query).toContain('bi_comparison_rank <= 51')
+ expect(probe.query).toMatch(/LIMIT 102$/)
})
it.each([undefined, '-1y'])(
diff --git a/products/business_intelligence/frontend/biAnalysis.ts b/products/business_intelligence/frontend/biAnalysis.ts
index 8efcb456d040..5955c115af4d 100644
--- a/products/business_intelligence/frontend/biAnalysis.ts
+++ b/products/business_intelligence/frontend/biAnalysis.ts
@@ -3,6 +3,8 @@ import { escapeHogQLString, escapeRawPropertyAsHogQLIdentifier } from '~/queries
import { ChartDisplayType } from '~/types'
import { biComparisonCategory } from './biComparison'
+import { limitBIComparisonQuery } from './biComparisonLimit'
+import { buildBIFilledPeriod, getBIMissingDatesDisabledReason } from './biTimeSeries'
export const BI_TABLE_CALCULATIONS: { value: BITableCalculation['type']; label: string }[] = [
{ value: 'percent_of_total', label: 'Percent of total' },
@@ -21,6 +23,7 @@ export function isBITableCalculation(value: unknown): value is BITableCalculatio
return (
BI_TABLE_CALCULATIONS.some(({ value }) => value === candidate.type) &&
(candidate.computeUsing === undefined || typeof candidate.computeUsing === 'string') &&
+ (candidate.requireFullWindow === undefined || typeof candidate.requireFullWindow === 'boolean') &&
(candidate.window === undefined ||
(Number.isInteger(candidate.window) && candidate.window >= 1 && candidate.window <= 1000))
)
@@ -30,6 +33,7 @@ export function isBIAnalysisConfig(config: Partial<BIConfig>): boolean {
const top = config.topN
const totals = config.totals
return (
+ (config.missingDates === undefined || ['gap', 'zero'].includes(config.missingDates)) &&
(top === undefined ||
(!!top &&
typeof top === 'object' &&
@@ -76,6 +80,8 @@ export interface BIAnalysisInput {
export function hasBIAnalysis(config: BIConfig): boolean {
return (
+ config.chartType === ChartDisplayType.TwoDimensionalHeatmap ||
+ (!!config.missingDates && !getBIMissingDatesDisabledReason(config)) ||
!!config.topN ||
!!config.resultFilters?.length ||
config.values.some((value) => !!value.tableCalculation) ||
@@ -115,8 +121,12 @@ function calculationExpression(
return `${column} - ${previous}`
case 'percent_change':
return `(${column} - ${previous}) * 1.0 / nullIf(abs(${previous}), 0)`
- case 'moving_average':
- return `avg(${column}) OVER (${window} ROWS BETWEEN ${Math.max(1, Math.min(1000, Math.trunc(calc.window ?? 3))) - 1} PRECEDING AND CURRENT ROW)`
+ case 'moving_average': {
+ const size = Math.max(1, Math.min(1000, Math.trunc(calc.window ?? 3)))
+ const frame = `${window} ROWS BETWEEN ${size - 1} PRECEDING AND CURRENT ROW`
+ const average = `avg(${column}) OVER (${frame})`
+ return `if(count(${column}) OVER (${frame}) ${calc.requireFullWindow ? `= ${size}` : '> 0'}, ${average}, NULL)`
+ }
case 'rank':
return `rank() OVER (${partitionBy}ORDER BY ${column} DESC)`
}
@@ -147,11 +157,28 @@ function groupingSets(config: BIConfig, input: BIAnalysisInput): string[][] {
sets.push([...rows, ...columns.slice(0, length)])
}
}
+ if (pivot) {
+ // Reaggregate every hierarchy intersection: averages and distinct counts cannot be summed from leaves.
+ for (let rowDepth = 1; rowDepth <= rows.length; rowDepth++) {
+ for (let columnDepth = 1; columnDepth <= columns.length; columnDepth++) {
+ sets.push([...rows.slice(0, rowDepth), ...columns.slice(0, columnDepth)])
+ }
+ if (config.totals?.rows) {
+ sets.push(rows.slice(0, rowDepth))
+ }
+ }
+ if (config.totals?.columns) {
+ for (let depth = 1; depth <= columns.length; depth++) {
+ sets.push(columns.slice(0, depth))
+ }
+ }
+ }
return [...new Map(sets.map((set) => [JSON.stringify(set), set])).values()]
}
export function buildBIAnalysisQuery(config: BIConfig, input: BIAnalysisInput): string {
const dimensions = [...input.rows, ...input.columns]
+ const pivot = config.chartType === ChartDisplayType.TwoDimensionalHeatmap
const ctes: string[] = []
const topMeasure = config.values.length
? input.measures.find((measure) => measure.value === config.values[config.topN?.measureIndex ?? 0])
@@ -171,31 +198,35 @@ export function buildBIAnalysisQuery(config: BIConfig, input: BIAnalysisInput):
? `(${topDimension.expression} IN (SELECT bi_key FROM bi_top) OR (${topDimension.expression} IS NULL AND (SELECT count(*) FROM bi_top WHERE bi_key IS NULL) > 0))`
: ''
for (const previous of periods) {
- const projection = dimensions.map((dimension, index) => {
+ const expressions = dimensions.map((dimension, index) => {
let expression = previous ? input.previousDimensions![index] : dimension.expression
if (config.topN && dimension === topDimension && config.topN.includeOther) {
// A tagged array keeps an actual category named "Other" distinct from the remainder.
expression = `if(${topMember}, ['0', toString(${expression})], ['1', 'Other'])`
}
- return `${expression} AS ${dimension.alias}`
+ return expression
})
const where = previous ? input.previousWhere! : input.where
const topFilter = config.topN && topDimension && !config.topN.includeOther ? ` AND ${topMember}` : ''
const select = [
- ...projection,
+ ...expressions.map((expression, index) => `${expression} AS ${aliases[index]}`),
...input.measures.map(
(measure) => `${measure.expression} AS ${escapeRawPropertyAsHogQLIdentifier(measure.alias)}`
),
...(totals
? [
- `grouping(${aliases.join(', ')}) AS bi_grouping`,
- ...aliases.map((alias, index) => `grouping(${alias}) AS ${groupingFlags[index]}`),
+ `grouping(${expressions.join(', ')}) AS bi_grouping`,
+ ...expressions.map((expression, index) => `grouping(${expression}) AS ${groupingFlags[index]}`),
]
: []),
]
ctes.push(
`bi_${previous ? 'previous' : 'current'} AS (SELECT ${select.join(', ')} FROM ${input.from} WHERE ${where}${topFilter}${dimensions.length ? ` GROUP BY ${totals ? `GROUPING SETS (${sets.map((set) => `(${set.join(', ')})`).join(', ')})` : aliases.join(', ')}` : ''})`
)
+ const filled = buildBIFilledPeriod(config, input, previous, totals)
+ if (filled) {
+ ctes.push(filled)
+ }
}
const calculations = input.measures.map((measure) => {
const expression = calculationExpression(measure, dimensions, totals ? ['bi_grouping'] : [])
@@ -203,7 +234,7 @@ export function buildBIAnalysisQuery(config: BIConfig, input: BIAnalysisInput):
})
const comparisonLabel = config.compareFilter?.compare_to ? 'Comparison period' : 'Previous period'
const periodQuery = (previous: boolean): string =>
- `SELECT ${[...aliases, ...calculations, ...(totals ? ['bi_grouping', ...groupingFlags] : []), ...(input.previousWhere ? [`${escapeHogQLString(previous ? comparisonLabel : 'Current period')} AS bi_period`] : [])].join(', ')} FROM bi_${previous ? 'previous' : 'current'}`
+ `SELECT ${[...aliases, ...calculations, ...(totals ? ['bi_grouping', ...groupingFlags] : []), ...(input.previousWhere ? [`${escapeHogQLString(previous ? comparisonLabel : 'Current period')} AS bi_period`] : [])].join(', ')} FROM bi_${previous ? 'previous' : 'current'}${config.missingDates && !getBIMissingDatesDisabledReason(config) ? '_filled' : ''}`
ctes.push(`bi_calculated AS (${periods.map(periodQuery).join(' UNION ALL ')})`)
const results = input.resultWhere ? 'bi_filtered' : 'bi_calculated'
if (input.resultWhere) {
@@ -216,12 +247,13 @@ export function buildBIAnalysisQuery(config: BIConfig, input: BIAnalysisInput):
if (dimension === topDimension && config.topN?.includeOther) {
expression = `if(${expression}[1] = '1', 'Other', if(startsWith(${expression}[2], 'Other'), concat(${expression}[2], ' (category)'), ${expression}[2]))`
}
- return totals
- ? `if(${groupingFlags[index]} != 0, 'Total', if(startsWith(toString(${expression}), 'Total'), concat(toString(${expression}), ' (category)'), toString(${expression})))`
- : expression
+ const label =
+ totals || pivot || config.totals?.subtotals
+ ? `if(startsWith(toString(${expression}), 'Total'), concat(toString(${expression}), ' (category)'), toString(${expression}))`
+ : expression
+ return totals ? `if(${groupingFlags[index]} != 0, 'Total', ${label})` : label
}
const displayed = dimensions.map(displayedDimension)
- const pivot = config.chartType === ChartDisplayType.TwoDimensionalHeatmap
const axis = (side: 'rows' | 'columns'): string[] => {
const fields = input[side]
if (!fields.length) {
@@ -254,6 +286,18 @@ export function buildBIAnalysisQuery(config: BIConfig, input: BIAnalysisInput):
order = `${dimension.alias} ${order.endsWith(' ASC') ? 'ASC' : 'DESC'}`
}
}
+ if (input.previousWhere) {
+ const query = `WITH ${ctes.join(',\n')} SELECT ${[...select, ...(totals ? ['bi_grouping AS bi_comparison_grouping'] : [])].join(', ')} FROM ${results}`
+ return limitBIComparisonQuery({
+ query,
+ config,
+ columns: [...aliases, ...input.measures.map(({ alias }) => alias), 'bi_comparison'],
+ dimensions: aliases,
+ order,
+ probe: (input.resultLimit ?? config.limit) > config.limit,
+ grouping: totals ? 'bi_comparison_grouping' : undefined,
+ })
+ }
if (totals) {
// Reserve at least half the result budget for detail cells when summaries alone exceed it.
ctes.push(
diff --git a/products/business_intelligence/frontend/biComparison.ts b/products/business_intelligence/frontend/biComparison.ts
index 0697f4f552ee..b290ea72ea87 100644
--- a/products/business_intelligence/frontend/biComparison.ts
+++ b/products/business_intelligence/frontend/biComparison.ts
@@ -26,9 +26,11 @@ export function getBIComparisonDisabledReason(config: BIConfig): string | undefi
ChartDisplayType.ActionsStackedBar,
ChartDisplayType.ActionsLineGraph,
ChartDisplayType.ActionsAreaGraph,
+ ChartDisplayType.BoldNumber,
+ ChartDisplayType.Metric,
].includes(config.chartType)
) {
- return 'Use a table, bar, line, or area chart for period comparisons'
+ return 'Use a table, KPI, bar, line, or area chart for period comparisons'
}
}
diff --git a/products/business_intelligence/frontend/biComparisonLimit.ts b/products/business_intelligence/frontend/biComparisonLimit.ts
new file mode 100644
index 000000000000..5a8782e8d198
--- /dev/null
+++ b/products/business_intelligence/frontend/biComparisonLimit.ts
@@ -0,0 +1,53 @@
+import { BIConfig } from '~/queries/schema/schema-business-intelligence'
+import { escapeRawPropertyAsHogQLIdentifier } from '~/queries/utils'
+
+export function getBIComparisonGroupLimit(config: BIConfig): number {
+ // Keep room for both periods without exceeding the backend's row cap.
+ return Math.floor(config.limit / 2)
+}
+
+export function limitBIComparisonQuery({
+ query,
+ config,
+ columns,
+ dimensions,
+ order,
+ probe,
+ grouping,
+}: {
+ query: string
+ config: BIConfig
+ columns: string[]
+ dimensions: string[]
+ order: string | null
+ probe: boolean
+ grouping?: string
+}): string {
+ const keys = dimensions.map(escapeRawPropertyAsHogQLIdentifier)
+ const partition = keys.length ? `PARTITION BY ${keys.join(', ')}` : ''
+ const sort = order?.match(/^(.*) (ASC|DESC)$/)
+ const score = sort
+ ? `coalesce(max(if(substring(bi_comparison, 1, 14) = 'Current period', ${sort[1]}, NULL)) OVER (${partition}), max(${sort[1]}) OVER (${partition}))`
+ : '1'
+ const ranking = [
+ ...(grouping ? [`${grouping} DESC`] : []),
+ `bi_comparison_sort ${sort?.[2] ?? 'ASC'}`,
+ ...keys.map((key) => `${key} ASC`),
+ ].join(', ')
+ const ctes = [
+ `bi_comparison_data AS (${query})`,
+ `bi_comparison_scored AS (SELECT *, ${score} AS bi_comparison_sort FROM bi_comparison_data)`,
+ ]
+ const groupLimit = getBIComparisonGroupLimit(config)
+ if (grouping) {
+ ctes.push(
+ `bi_comparison_summaries AS (SELECT *, dense_rank() OVER (PARTITION BY ${grouping} = 0 ORDER BY ${ranking}) AS bi_summary_rank FROM bi_comparison_scored)`,
+ `bi_comparison_budget AS (SELECT * FROM bi_comparison_summaries WHERE ${grouping} = 0 OR bi_summary_rank <= ${Math.floor(groupLimit / 2)})`
+ )
+ }
+ ctes.push(
+ `bi_comparison_ranked AS (SELECT *, dense_rank() OVER (ORDER BY ${ranking}) AS bi_comparison_rank FROM ${grouping ? 'bi_comparison_budget' : 'bi_comparison_scored'})`
+ )
+ const requestedGroups = groupLimit + (probe ? 1 : 0)
+ return `WITH ${ctes.join(',\n')} SELECT ${columns.map(escapeRawPropertyAsHogQLIdentifier).join(', ')} FROM bi_comparison_ranked WHERE bi_comparison_rank <= ${requestedGroups} ORDER BY bi_comparison_rank ASC, bi_comparison ASC LIMIT ${requestedGroups * 2}`
+}
diff --git a/products/business_intelligence/frontend/biComparisonResults.test.ts b/products/business_intelligence/frontend/biComparisonResults.test.ts
new file mode 100644
index 000000000000..04b1271133cb
--- /dev/null
+++ b/products/business_intelligence/frontend/biComparisonResults.test.ts
@@ -0,0 +1,96 @@
+import { BIVisualizationNode } from '~/queries/schema/schema-business-intelligence'
+import { HogQLQueryResponse, NodeKind } from '~/queries/schema/schema-general'
+import { ChartDisplayType } from '~/types'
+
+import { buildBIComparisonRows, getBIComparisonValues } from './biComparisonResults'
+import { buildBIQuery, DEFAULT_BI_CONFIG } from './biEditorTypes'
+import { getBIVisualizationResponse } from './biQueryResults'
+
+it.each([
+ ['positive', 150, 100, 50, 0.5],
+ ['negative', -50, -100, 50, 0.5],
+ ['zero baseline', 10, 0, 10, null],
+ ['missing baseline', 10, null, null, null],
+ ['missing current', null, 10, null, null],
+] as const)(
+ 'compares KPI values with a %s baseline without inventing missing values',
+ (_name, current, previous, change, percent) => {
+ const config = {
+ ...DEFAULT_BI_CONFIG,
+ source: { table: 'events' },
+ dateRange: { date_from: '-7d' },
+ compareFilter: { compare: true },
+ chartType: ChartDisplayType.BoldNumber,
+ }
+ expect(buildBIQuery(config)!.query).toContain('Previous period')
+ const rows = buildBIComparisonRows(
+ config,
+ ['count', 'bi_comparison'],
+ [
+ [previous, 'Previous period'],
+ [current, 'Current period'],
+ ]
+ )
+ expect(rows).toHaveLength(1)
+ expect(getBIComparisonValues(rows[0], 'count')).toEqual({ current, previous, change, percent })
+ }
+)
+
+it('pairs comparison rows by dimensions and preserves periods that only have one side', () => {
+ const config = {
+ ...DEFAULT_BI_CONFIG,
+ compareFilter: { compare: true },
+ rows: [
+ { id: 'event', expression: 'event', name: 'event', source: { table: 'events' }, type: 'string' as const },
+ ],
+ }
+ const rows = buildBIComparisonRows(
+ config,
+ ['bi_row_event', 'count', 'bi_comparison'],
+ [
+ ['purchase', 10, 'Previous period'],
+ ['signup', 3, 'Current period'],
+ ['purchase', 15, 'Current period'],
+ ['old', 4, 'Previous period'],
+ ]
+ )
+ expect(rows.map((row) => [row.dimensions[0], getBIComparisonValues(row, 'count').change])).toEqual([
+ ['purchase', 5],
+ ['signup', null],
+ ['old', null],
+ ])
+ expect(rows[0].previous?.bi_comparison).toBe('Previous period')
+})
+
+it.each([true, false])('trims the probe by whole dimension groups (both periods present: %s)', (bothPeriods) => {
+ const config = {
+ ...DEFAULT_BI_CONFIG,
+ limit: 100 as const,
+ compareFilter: { compare: true },
+ rows: [
+ { id: 'event', expression: 'event', name: 'event', source: { table: 'events' }, type: 'string' as const },
+ ],
+ }
+ const current = Array.from({ length: 51 }, (_, index) => [
+ index === 0 ? null : `group ${index}`,
+ 20,
+ 'Current period',
+ ])
+ const previous = bothPeriods ? current.map(([group]) => [group, 10, 'Previous period']) : []
+ const response = getBIVisualizationResponse(
+ { kind: NodeKind.BIVisualizationNode, config } as BIVisualizationNode,
+ {
+ columns: ['bi_row_event', 'count', 'bi_comparison'],
+ results: [...current, ...previous],
+ } as HogQLQueryResponse
+ ) as HogQLQueryResponse
+ const rows = buildBIComparisonRows(config, response.columns ?? [], response.results)
+ expect(rows).toHaveLength(50)
+ expect(rows[0].dimensions).toEqual([null])
+ expect(getBIComparisonValues(rows[49], 'count')).toMatchObject({
+ current: 20,
+ previous: bothPeriods ? 10 : null,
+ change: bothPeriods ? 10 : null,
+ })
+ expect(response.hasMore).toBe(true)
+})
diff --git a/products/business_intelligence/frontend/biComparisonResults.ts b/products/business_intelligence/frontend/biComparisonResults.ts
new file mode 100644
index 000000000000..e4f8691b1c4c
--- /dev/null
+++ b/products/business_intelligence/frontend/biComparisonResults.ts
@@ -0,0 +1,44 @@
+import { BIConfig } from '~/queries/schema/schema-business-intelligence'
+
+import { getBIResultDimensions } from './biEditorTypes'
+import { biNumericValue } from './biResultPresentation'
+
+export interface BIComparisonRow {
+ key: string
+ dimensions: unknown[]
+ current?: Record<string, unknown>
+ previous?: Record<string, unknown>
+}
+
+export function buildBIComparisonRows(config: BIConfig, columns: string[], results: unknown[][]): BIComparisonRow[] {
+ const dimensions = getBIResultDimensions(config)
+ const groups = new Map<string, BIComparisonRow>()
+ for (const result of results) {
+ const record = Object.fromEntries(columns.map((column, index) => [column, result[index]]))
+ const values = dimensions.map(({ column }) => record[column])
+ const key = JSON.stringify(values)
+ const row = groups.get(key) ?? { key, dimensions: values }
+ if (/^(Previous|Comparison) period(?: · |$)/.test(String(record.bi_comparison))) {
+ row.previous = record
+ } else {
+ row.current = record
+ }
+ groups.set(key, row)
+ }
+ return [...groups.values()]
+}
+
+export function getBIComparisonValues(
+ row: BIComparisonRow,
+ column: string
+): { current: number | null; previous: number | null; change: number | null; percent: number | null } {
+ const current = biNumericValue(row.current?.[column])
+ const previous = biNumericValue(row.previous?.[column])
+ const change = current === null || previous === null ? null : current - previous
+ return {
+ current,
+ previous,
+ change,
+ percent: change === null || previous === null || previous === 0 ? null : change / Math.abs(previous),
+ }
+}
diff --git a/products/business_intelligence/frontend/biDrilldown.ts b/products/business_intelligence/frontend/biDrilldown.ts
index b38106d71f5b..27722fa7dad6 100644
--- a/products/business_intelligence/frontend/biDrilldown.ts
+++ b/products/business_intelligence/frontend/biDrilldown.ts
@@ -87,7 +87,12 @@ export function getBIDrillSelection(config: BIConfig, record: Record<string, unk
continue
}
const displayValue = value
- if (config.totals?.rows || config.totals?.columns || config.totals?.subtotals) {
+ if (
+ config.chartType === ChartDisplayType.TwoDimensionalHeatmap ||
+ config.totals?.rows ||
+ config.totals?.columns ||
+ config.totals?.subtotals
+ ) {
if (value === 'Total') {
continue
}
diff --git a/products/business_intelligence/frontend/biEditorAnalytics.ts b/products/business_intelligence/frontend/biEditorAnalytics.ts
index 653ce9b242a1..4723f9dacef8 100644
--- a/products/business_intelligence/frontend/biEditorAnalytics.ts
+++ b/products/business_intelligence/frontend/biEditorAnalytics.ts
@@ -58,6 +58,10 @@ function getBIEditorConfigProperties(config: BIConfig): Record<string, unknown>
top_n_count: config.topN?.count ?? null,
top_n_include_other: config.topN?.includeOther ?? false,
comparison_enabled: !!config.compareFilter?.compare,
+ missing_dates: config.missingDates ?? 'observed',
+ full_window_measure_count: config.values.filter(
+ (value) => value.tableCalculation?.type === 'moving_average' && value.tableCalculation.requireFullWindow
+ ).length,
comparison_period: config.compareFilter?.compare
? config.compareFilter.compare_to
? 'custom_offset'
@@ -95,11 +99,19 @@ export type BIWorksheetAction =
| 'related_table_expanded'
| 'properties_browsed'
| 'properties_searched'
+ | 'pivot_hierarchy_toggled'
export function captureBIWorksheetAction(
action: BIWorksheetAction,
config: BIConfig,
- context: { insight_id?: number; previous_period?: boolean; result_count?: number } = {}
+ context: {
+ insight_id?: number
+ previous_period?: boolean
+ result_count?: number
+ hierarchy_axis?: 'rows' | 'columns'
+ hierarchy_depth?: number
+ expanded?: boolean
+ } = {}
): void {
posthog.capture(BI_EDITOR_EVENTS.WORKSHEET_ACTION, {
action,
diff --git a/products/business_intelligence/frontend/biEditorLogic.ts b/products/business_intelligence/frontend/biEditorLogic.ts
index 532bf21b9826..48d43f38de36 100644
--- a/products/business_intelligence/frontend/biEditorLogic.ts
+++ b/products/business_intelligence/frontend/biEditorLogic.ts
@@ -477,6 +477,9 @@ export interface biEditorLogicActions {
setLimit: (limit: BIQueryLimit) => {
limit: BIQueryLimit
}
+ setMissingDates: (missingDates: BIConfig['missingDates']) => {
+ missingDates: 'gap' | 'zero' | undefined
+ }
setShowMeOpen: (showMeOpen: boolean) => {
showMeOpen: boolean
}
@@ -631,6 +634,7 @@ export const biEditorLogic = kea<biEditorLogicType>([
setChartType: (chartType: ChartDisplayType) => ({ chartType }),
setDateRange: (dateRange: DateRange) => ({ dateRange }),
setCompareFilter: (compareFilter: CompareFilter) => ({ compareFilter }),
+ setMissingDates: (missingDates: BIConfig['missingDates']) => ({ missingDates }),
setDateField: (field: BIField | null) => ({ field }),
setDataSource: (source: BIDataSource) => ({ source }),
setValueAggregation: (index: number, aggregation: BIAggregation) => ({ index, aggregation }),
@@ -786,6 +790,7 @@ export const biEditorLogic = kea<biEditorLogicType>([
setChartType: (config, { chartType }) => normalizeBIConfig({ ...config, chartType }),
setDateRange: (config, { dateRange }) => ({ ...config, dateRange }),
setCompareFilter: (config, { compareFilter }) => ({ ...config, compareFilter }),
+ setMissingDates: (config, { missingDates }) => ({ ...config, missingDates }),
setDateField: (config, { field }) => ({ ...config, dateField: field }),
setDataSource: (config, { source }) => setDataSourceInConfig(config, source),
setValueAggregation: (config, { index, aggregation }) => ({
@@ -1018,6 +1023,7 @@ export const biEditorLogic = kea<biEditorLogicType>([
setChartType: () => actions.runAfterChange(),
setDateRange: () => actions.runAfterChange(),
setCompareFilter: () => actions.runAfterChange(),
+ setMissingDates: () => actions.runAfterChange(),
setDateField: () => actions.runAfterChange(),
setDataSource: () => {
captureBIWorksheetAction('source_selected', values.config)
diff --git a/products/business_intelligence/frontend/biEditorTypes.test.ts b/products/business_intelligence/frontend/biEditorTypes.test.ts
index 7b688db69d67..b952d0233d07 100644
--- a/products/business_intelligence/frontend/biEditorTypes.test.ts
+++ b/products/business_intelligence/frontend/biEditorTypes.test.ts
@@ -92,7 +92,8 @@ describe('BI editor query generation', () => {
expect(result.query).toContain('UNION ALL')
expect(result.query).toContain('toStartOfDay({filters.compareDate(timestamp)}) AS bi_row_timestamp')
expect(result.query).toContain('{filters.previous}')
- expect(result.query).toContain('ORDER BY bi_row_timestamp DESC')
+ expect(result.query).toContain("'Current period', bi_row_timestamp, NULL")
+ expect(result.query).toContain('ORDER BY bi_comparison_sort DESC, bi_row_timestamp ASC')
expect(result.node.chartSettings?.seriesBreakdownColumn).toBe('bi_comparison')
expect(parseBIEditorState(BIEditorView.BI, config)?.config.compareFilter).toEqual(config.compareFilter)
expect(buildBIQuery({ ...config, dateRange: { date_from: 'all' } })?.query).not.toContain('UNION ALL')
@@ -398,12 +399,13 @@ describe('BI editor query generation', () => {
limit,
})
- expect(result?.query).toContain('toJSONString(tuple(event, timestamp)) AS bi_rows')
- expect(result?.query).toContain(
- 'toJSONString(tuple(properties.$browser, properties.$geoip_country_name)) AS bi_columns'
- )
+ expect(result?.query).toContain('event AS bi_row_event, timestamp AS bi_row_timestamp_2')
+ expect(result?.query).toContain('properties.$browser AS bi_column_browser')
+ expect(result?.query).toContain('properties.$geoip_country_name AS bi_column_country_2')
+ expect(result?.query).toMatch(/toJSONString\(tuple\(.*\)\) AS bi_rows/)
+ expect(result?.query).toMatch(/toJSONString\(tuple\(.*\)\) AS bi_columns/)
expect(result?.query).toContain(`LIMIT ${limit}`)
- expect(result?.node.chartSettings).toEqual({
+ expect(result?.node.chartSettings).toMatchObject({
heatmap: {
xAxisColumn: 'bi_columns',
yAxisColumn: 'bi_rows',
@@ -540,7 +542,7 @@ describe('BI editor query generation', () => {
const result = buildBIQuery(config)!
expect(result.query).toContain('sum(properties.revenue) AS sum_revenue_2,')
expect(result.query).toContain('sum(properties.revenue) AS sum_revenue_2_2,')
- expect(result.query).toContain('ORDER BY\n sum_revenue_2_2 ASC')
+ expect(result.query).toMatch(/ORDER BY\s+sum_revenue_2_2 ASC/)
expect(getBISortOptions(config).find(({ key }) => key === config.sort?.key)?.expression).toBe(
'sum_revenue_2_2'
)
@@ -757,7 +759,7 @@ describe('BI editor query generation', () => {
columns: [countryField],
values: Array.from({ length: measureCount }, () => ({ field: revenueField, aggregation: 'sum' })),
}
- expect(getBIChartFit(pivotConfig, ChartDisplayType.TwoDimensionalHeatmap).fits).toBe(measureCount <= 1)
+ expect(getBIChartFit(pivotConfig, ChartDisplayType.TwoDimensionalHeatmap).fits).toBe(true)
expect(buildBIQuery(pivotConfig)?.node.chartSettings?.heatmap?.valueColumn).toBe(
measureCount === 0 ? 'count' : 'sum_revenue'
)
diff --git a/products/business_intelligence/frontend/biEditorTypes.ts b/products/business_intelligence/frontend/biEditorTypes.ts
index 8816e58f9cc2..410f5e9e7b97 100644
--- a/products/business_intelligence/frontend/biEditorTypes.ts
+++ b/products/business_intelligence/frontend/biEditorTypes.ts
@@ -37,6 +37,7 @@ import {
isBITableCalculation,
} from './biAnalysis'
import { biComparisonCategory, getBIComparisonDisabledReason, getBIComparisonDateExpression } from './biComparison'
+import { limitBIComparisonQuery } from './biComparisonLimit'
import {
buildBIConditionExpression,
isBIConditionGroup,
@@ -377,8 +378,8 @@ export function getBIChartFit(config: BIConfig, chartType: ChartDisplayType): BI
}
case ChartDisplayType.TwoDimensionalHeatmap:
return {
- fits: rowCount >= 1 && columnCount >= 1 && config.values.length <= 1,
- requirement: '1 or more dimensions on rows and on columns, and up to 1 measure',
+ fits: rowCount >= 1 && columnCount >= 1,
+ requirement: '1 or more dimensions on rows and on columns, and any measures',
}
case ChartDisplayType.BoldNumber:
case ChartDisplayType.Metric:
@@ -611,6 +612,7 @@ export function parseBIEditorState(editorViewValue: unknown, configValue: unknow
...(candidate.resultFilters ? { resultFilters: candidate.resultFilters } : {}),
...(candidate.topN ? { topN: candidate.topN } : {}),
...(candidate.totals ? { totals: candidate.totals } : {}),
+ ...(candidate.missingDates ? { missingDates: candidate.missingDates } : {}),
...(candidate.compareFilter !== undefined ? { compareFilter: candidate.compareFilter } : {}),
...(candidate.dateField !== undefined
? { dateField: candidate.dateField === null ? null : parseBIFieldValue(candidate.dateField) }
@@ -1039,6 +1041,13 @@ export function getBIResultDimensions(config: BIConfig): { field: BIField; colum
return dimensions.map(({ field, alias }) => ({ field, column: aliased ? alias : fieldExpression(field) }))
}
+export function getBIResultMeasureColumns(config: BIConfig): { column: string; value?: BIValue }[] {
+ const { configuredValues } = computeBIQueryParts(config)
+ return configuredValues.length
+ ? configuredValues.map(({ alias, value }) => ({ column: alias, value }))
+ : [{ column: 'count' }]
+}
+
export function buildBIRowsQuery(config: BIConfig, previous = false): HogQLQuery | null {
if (!config.source || config.filters.some(getBIFilterValidationError)) {
return null
@@ -1318,11 +1327,20 @@ export function buildBIQuery(config: BIConfig, probeForMoreRows = false): BIQuer
`FROM ${escapePropertyAsHogQLIdentifier(config.source!.table)}`,
`WHERE\n ${[previous ? placeholder.replace('{filters', '{filters.previous') : placeholder, ...filters.map((filter) => `(${filter})`)].join('\n AND ')}`,
...(expressions.length ? [`GROUP BY ${[...expressions, 'bi_comparison'].join(', ')}`] : []),
- ...(comparisonOrder ? [`ORDER BY ${comparisonOrder}`] : []),
- `LIMIT ${resultLimit}`,
].join('\n')
}
- query = `SELECT * FROM ((${buildPeriod(false)})\nUNION ALL\n(${buildPeriod(true)})) LIMIT ${resultLimit}`
+ query = limitBIComparisonQuery({
+ query: `(${buildPeriod(false)})\nUNION ALL\n(${buildPeriod(true)})`,
+ config,
+ columns: [
+ ...dimensions.map(({ alias }) => alias),
+ ...(configuredValues.length ? configuredValues.map(({ alias }) => alias) : ['count']),
+ 'bi_comparison',
+ ],
+ dimensions: dimensions.map(({ alias }) => alias),
+ order: comparisonOrder,
+ probe: probeForMoreRows,
+ })
seriesSettings = {
xAxis: { column: xDimension?.alias ?? 'bi_comparison' },
xAxisLabel: xDimension ? getBIFieldPillLabel(xDimension.field) : 'Period',
@@ -1395,6 +1413,9 @@ export function buildBIQuery(config: BIConfig, probeForMoreRows = false): BIQuer
column: alias,
settings: getBIMeasureSettings(value),
}))
+ if (config.missingDates) {
+ seriesSettings = { ...seriesSettings, showNullsAsZero: false }
+ }
if (calculatedFormats.length) {
seriesSettings = {
...seriesSettings,
diff --git a/products/business_intelligence/frontend/biPivot.test.ts b/products/business_intelligence/frontend/biPivot.test.ts
new file mode 100644
index 000000000000..245881bffb85
--- /dev/null
+++ b/products/business_intelligence/frontend/biPivot.test.ts
@@ -0,0 +1,60 @@
+import { BIConfig, BIField } from '~/queries/schema/schema-business-intelligence'
+import { ChartDisplayType } from '~/types'
+
+import { getBIDrillSelection } from './biDrilldown'
+import { DEFAULT_BI_CONFIG } from './biEditorTypes'
+import { biPivotCellKey, buildBIPivotModel, visibleBIPivotMembers } from './biPivot'
+
+const field = (name: string): BIField => ({
+ id: name,
+ name,
+ expression: name,
+ type: 'string',
+ source: { table: 'events' },
+})
+
+it('keeps reaggregated multi-measure hierarchy cells and their drill-down dimensions when collapsed', () => {
+ const config: BIConfig = {
+ ...DEFAULT_BI_CONFIG,
+ source: { table: 'events' },
+ chartType: ChartDisplayType.TwoDimensionalHeatmap,
+ rows: [field('region'), field('city')],
+ columns: [field('year'), field('quarter')],
+ totals: { rows: true, columns: true },
+ values: [
+ { field: field('amount'), aggregation: 'average' },
+ { field: field('user'), aggregation: 'count_distinct' },
+ ],
+ }
+ const model = buildBIPivotModel(
+ config,
+ ['bi_rows', 'bi_columns', 'average_amount', 'count_distinct_user_2'],
+ [
+ ['["Europe","Total"]', '["2026","Total"]', 17.5, 3],
+ ['["Europe","Paris"]', '["2026","Q1"]', 10, 2],
+ ['["Europe","Rome"]', '["2026","Q1"]', 20, 2],
+ ['["Total","Total"]', '["Total","Total"]', 17.5, 3],
+ ['["Total (category)",null]', '["2026","Q1"]', 8, 1],
+ ]
+ )
+ const collapsed = visibleBIPivotMembers(model.rows, new Set(['["Europe"]']), true)
+ expect(collapsed.map((row) => row.label)).toEqual(['Europe', 'Total (category)', '(empty)', 'Total'])
+ expect(visibleBIPivotMembers(model.columns, new Set(['["2026"]']), false).map((row) => row.label)).toEqual([
+ '2026',
+ 'Total',
+ ])
+ const record = model.cells.get(biPivotCellKey(['Europe'], ['2026']))!
+ expect(record.average_amount).toBe(17.5)
+ expect(record.count_distinct_user_2).toBe(3)
+ expect(getBIDrillSelection(config, record).filters.map(({ field, value }) => [field.name, value])).toEqual([
+ ['region', 'Europe'],
+ ['year', '2026'],
+ ])
+ const empty = model.cells.get(biPivotCellKey(['Total (category)', null], ['2026', 'Q1']))!
+ expect(getBIDrillSelection(config, empty).filters.map(({ operator, value }) => [operator, value])).toEqual([
+ ['equals', 'Total'],
+ ['is_not_set', ''],
+ ['equals', '2026'],
+ ['equals', 'Q1'],
+ ])
+})
diff --git a/products/business_intelligence/frontend/biPivot.ts b/products/business_intelligence/frontend/biPivot.ts
new file mode 100644
index 000000000000..b7559ceb4711
--- /dev/null
+++ b/products/business_intelligence/frontend/biPivot.ts
@@ -0,0 +1,108 @@
+import { BIConfig } from '~/queries/schema/schema-business-intelligence'
+
+import { getBIResultDimensions } from './biEditorTypes'
+
+export interface BIPivotMember {
+ key: string
+ path: unknown[]
+ label: string
+ children: BIPivotMember[]
+}
+
+export interface BIPivotModel {
+ rows: BIPivotMember[]
+ columns: BIPivotMember[]
+ cells: Map<string, Record<string, unknown>>
+}
+
+export function biPivotKey(path: unknown[]): string {
+ return JSON.stringify(path)
+}
+
+export function biPivotCellKey(row: unknown[], column: unknown[]): string {
+ return JSON.stringify([row, column])
+}
+
+export function buildBIPivotModel(config: BIConfig, columns: string[], results: unknown[][]): BIPivotModel {
+ const dimensions = getBIResultDimensions(config)
+ const rowCount = config.rows.filter((field) => field.expression.trim() || field.name.trim()).length
+ const columnCount = config.columns.filter((field) => field.expression.trim() || field.name.trim()).length
+ const summaries = rowCount > 1 || columnCount > 1 || !!(config.totals?.rows || config.totals?.columns)
+ const model: BIPivotModel = { rows: [], columns: [], cells: new Map() }
+ const indexes = new Map(columns.map((column, index) => [column, index]))
+ const members = { rows: new Map<string, BIPivotMember>(), columns: new Map<string, BIPivotMember>() }
+ const readPath = (row: unknown[], side: 'rows' | 'columns'): unknown[] => {
+ const fields = side === 'rows' ? dimensions.slice(0, rowCount) : dimensions.slice(rowCount)
+ const values = fields.map(({ column, position }) => {
+ const value = row[indexes.get(column)!]
+ if (position === undefined) {
+ return value
+ }
+ try {
+ const tuple = typeof value === 'string' ? JSON.parse(value) : value
+ return Array.isArray(tuple) ? tuple[position] : undefined
+ } catch {
+ return undefined
+ }
+ })
+ const depth = summaries ? values.indexOf('Total') : -1
+ return depth === -1 ? values : values.slice(0, depth)
+ }
+ const addPath = (path: unknown[], side: 'rows' | 'columns'): void => {
+ if (!path.length) {
+ if (!(side === 'rows' ? config.totals?.columns : config.totals?.rows) || members[side].has('[]')) {
+ return
+ }
+ const total = { key: '[]', path, label: 'Total', children: [] }
+ members[side].set('[]', total)
+ model[side].push(total)
+ }
+ for (let depth = 1; depth <= path.length; depth++) {
+ const prefix = path.slice(0, depth)
+ const key = biPivotKey(prefix)
+ if (!members[side].has(key)) {
+ const member: BIPivotMember = {
+ key,
+ path: prefix,
+ label: String(prefix[depth - 1] ?? '(empty)'),
+ children: [],
+ }
+ members[side].set(key, member)
+ const siblings =
+ depth === 1 ? model[side] : members[side].get(biPivotKey(prefix.slice(0, -1)))!.children
+ siblings.push(member)
+ }
+ }
+ }
+ for (const result of results) {
+ const row = readPath(result, 'rows')
+ const column = readPath(result, 'columns')
+ addPath(row, 'rows')
+ addPath(column, 'columns')
+ model.cells.set(
+ biPivotCellKey(row, column),
+ Object.fromEntries(columns.map((name, index) => [name, result[index]]))
+ )
+ }
+ // Grand totals stay after their detail members, regardless of query sorting.
+ for (const side of ['rows', 'columns'] as const) {
+ model[side].sort((a, b) => Number(!a.path.length) - Number(!b.path.length))
+ }
+ return model
+}
+
+export function visibleBIPivotMembers(
+ members: BIPivotMember[],
+ collapsed: Set<string>,
+ includeParents: boolean
+): BIPivotMember[] {
+ return members.flatMap((member) => {
+ if (!member.children.length || collapsed.has(member.key)) {
+ return [member]
+ }
+ return [
+ ...(includeParents ? [member] : []),
+ ...visibleBIPivotMembers(member.children, collapsed, includeParents),
+ ]
+ })
+}
diff --git a/products/business_intelligence/frontend/biQueryResults.ts b/products/business_intelligence/frontend/biQueryResults.ts
index ed65240c6658..af934b9fe219 100644
--- a/products/business_intelligence/frontend/biQueryResults.ts
+++ b/products/business_intelligence/frontend/biQueryResults.ts
@@ -1,6 +1,7 @@
import { AnyResponseType, NodeKind, VisualizationNode } from '~/queries/schema/schema-general'
-import { buildBIQuery } from './biEditorTypes'
+import { getBIComparisonGroupLimit } from './biComparisonLimit'
+import { buildBIQuery, getBIResultDimensions } from './biEditorTypes'
export function getBIVisualizationSource(query: VisualizationNode): VisualizationNode['source'] {
if (query.kind !== NodeKind.BIVisualizationNode) {
@@ -22,6 +23,18 @@ export function getBIVisualizationResponse(
) {
return response
}
+ if (query.config.compareFilter?.compare) {
+ const columns = 'columns' in response && Array.isArray(response.columns) ? response.columns : []
+ const dimensions = getBIResultDimensions(query.config).map(({ column }) => columns.indexOf(column))
+ const key = (row: unknown[]): string => JSON.stringify(dimensions.map((index) => row[index]))
+ const groups = new Set(response.results.map(key))
+ const selected = new Set([...groups].slice(0, getBIComparisonGroupLimit(query.config)))
+ return {
+ ...response,
+ results: response.results.filter((row) => selected.has(key(row))),
+ hasMore: groups.size > selected.size || ('hasMore' in response && response.hasMore === true),
+ }
+ }
return {
...response,
results: response.results.slice(0, query.config.limit),
diff --git a/products/business_intelligence/frontend/biResultPresentation.ts b/products/business_intelligence/frontend/biResultPresentation.ts
new file mode 100644
index 000000000000..9569db90e7ec
--- /dev/null
+++ b/products/business_intelligence/frontend/biResultPresentation.ts
@@ -0,0 +1,34 @@
+import { formatDataWithSettings } from '~/queries/nodes/DataVisualization/dataVisualizationLogic'
+import { BIConfig } from '~/queries/schema/schema-business-intelligence'
+import { ChartAxis, ChartSettings } from '~/queries/schema/schema-general'
+
+import { getBIResultMeasureColumns, getBIValuePillLabel } from './biEditorTypes'
+import { getBIMeasureSettings } from './biMeasureSettings'
+
+export function getBIResultMeasures(
+ config: BIConfig,
+ settings?: ChartSettings
+): { column: string; label: string; settings: ChartAxis['settings'] }[] {
+ return getBIResultMeasureColumns(config).map(({ column, value }) => ({
+ column,
+ label: value?.display?.label || (value ? getBIValuePillLabel(value) : 'Count'),
+ settings:
+ settings?.yAxis?.find((axis) => axis.column === column)?.settings ??
+ (value ? getBIMeasureSettings(value) : undefined),
+ }))
+}
+
+export function biNumericValue(value: unknown): number | null {
+ if (value === null || value === undefined || value === '') {
+ return null
+ }
+ const number = typeof value === 'number' ? value : typeof value === 'string' ? Number(value) : NaN
+ return Number.isFinite(number) ? number : null
+}
+
+export function formatBIMeasure(value: unknown, settings?: ChartAxis['settings']): string {
+ const number = biNumericValue(value)
+ return number === null
+ ? '—'
+ : String(formatDataWithSettings(number * (settings?.formatting?.style === 'percent' ? 100 : 1), settings))
+}
diff --git a/products/business_intelligence/frontend/biTimeSeries.ts b/products/business_intelligence/frontend/biTimeSeries.ts
new file mode 100644
index 000000000000..4b443265785f
--- /dev/null
+++ b/products/business_intelligence/frontend/biTimeSeries.ts
@@ -0,0 +1,74 @@
+import { BIConfig, BIDateBucket } from '~/queries/schema/schema-business-intelligence'
+import { escapeRawPropertyAsHogQLIdentifier } from '~/queries/utils'
+import { ChartDisplayType } from '~/types'
+
+import type { BIAnalysisInput } from './biAnalysis'
+import { getBIDateField } from './biQueryFilters'
+
+const BUCKET_START: Record<BIDateBucket, string> = {
+ minute: 'toStartOfMinute',
+ hour: 'toStartOfHour',
+ day: 'toStartOfDay',
+ week: 'toStartOfWeek',
+ month: 'toStartOfMonth',
+ quarter: 'toStartOfQuarter',
+ year: 'toStartOfYear',
+}
+
+export function getBIMissingDatesDisabledReason(config: BIConfig): string | undefined {
+ const dates = [...config.rows, ...config.columns].filter((field) => ['date', 'datetime'].includes(field.type))
+ if (dates.length !== 1 || !dates[0].dateBucket) {
+ return 'Add one date dimension with a time bucket first'
+ }
+ if (
+ getBIDateField(config)?.expression !== dates[0].expression ||
+ !config.dateRange?.date_from ||
+ config.dateRange.date_from === 'all'
+ ) {
+ return 'Use the date dimension as the date column and select a bounded date range'
+ }
+ if (config.source?.connectionId) {
+ return 'Date filling is available for project and warehouse tables'
+ }
+ if (
+ ![
+ ChartDisplayType.Auto,
+ ChartDisplayType.ActionsTable,
+ ChartDisplayType.ActionsLineGraph,
+ ChartDisplayType.ActionsAreaGraph,
+ ChartDisplayType.ActionsBar,
+ ChartDisplayType.ActionsStackedBar,
+ ].includes(config.chartType)
+ ) {
+ return 'Use a table or time-series chart to fill missing dates'
+ }
+}
+
+export function buildBIFilledPeriod(
+ config: BIConfig,
+ input: BIAnalysisInput,
+ previous: boolean,
+ totals: boolean
+): string | null {
+ if (!config.missingDates || getBIMissingDatesDisabledReason(config)) {
+ return null
+ }
+ const dimensions = [...input.rows, ...input.columns]
+ const date = dimensions.find(({ field }) => ['date', 'datetime'].includes(field.type))!
+ const bucket = date.field.dateBucket!
+ const start = BUCKET_START[bucket]
+ const period = `bi_${previous ? 'previous' : 'current'}`
+ const measures = input.measures.map(({ alias }) => escapeRawPropertyAsHogQLIdentifier(alias))
+ const select = [
+ ...dimensions.map(({ alias }) => alias),
+ ...measures.map((alias) => `toNullable(toFloat(${alias})) AS ${alias}`),
+ ...(totals ? ['bi_grouping', ...dimensions.map((_, index) => `bi_grouping_${index}`)] : []),
+ ].join(', ')
+ const order = [
+ ...dimensions.filter((dimension) => dimension !== date).map(({ alias }) => `${alias} ASC`),
+ `${date.alias} ASC WITH FILL FROM ${start}({filters.dateRange.from}) TO ${start}({filters.dateRange.to}) + INTERVAL 1 ${bucket.toUpperCase()} STEP INTERVAL 1 ${bucket.toUpperCase()}`,
+ ]
+ const interpolate =
+ config.missingDates === 'zero' ? ` INTERPOLATE (${measures.map((alias) => `${alias} AS 0`).join(', ')})` : ''
+ return `${period}_filled AS ((SELECT ${select} FROM ${period}${totals ? ' WHERE bi_grouping = 0' : ''} ORDER BY ${order.join(', ')}${interpolate})${totals ? ` UNION ALL SELECT ${select} FROM ${period} WHERE bi_grouping != 0` : ''})`
+}
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index 123fb056c70a..b1210aaf26ed 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -9439,6 +9439,13 @@ export const BIQueryLimitApi = {
Number50000: 50000,
} as const
+export type MissingDatesApi = (typeof MissingDatesApi)[keyof typeof MissingDatesApi]
+
+export const MissingDatesApi = {
+ Gap: 'gap',
+ Zero: 'zero',
+} as const
+
export type Operator1Api = (typeof Operator1Api)[keyof typeof Operator1Api]
export const Operator1Api = {
@@ -9529,6 +9536,8 @@ export const BITableCalculationTypeApi = {
export interface BITableCalculationApi {
/** Dimension ID to traverse. Unset chooses the date dimension; 'table' traverses all dimensions. */
computeUsing?: string | null
+ /** Require a complete window of non-null values before displaying a moving average. */
+ requireFullWindow?: boolean | null
type: BITableCalculationTypeApi
/** Number of points, including the current point, in a trailing moving average. */
window?: number | null
@@ -9553,6 +9562,8 @@ export interface BIConfigApi {
dateRange?: DateRangeApi | null
filters: BIFilterApi[]
limit: BIQueryLimitApi
+ /** Fill missing date buckets before table calculations. Unset preserves observed points only. */
+ missingDates?: MissingDatesApi | null
resultFilterGroup?: BIConditionGroupApi | null
resultFilters?: BIResultFilterApi[] | null
rowFilterGroup?: BIConditionGroupApi | null
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index 747d6426a592..7530a28fbd9a 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -8366,6 +8366,13 @@ export const BIQueryLimitApi = {
Number50000: 50000,
} as const
+export type MissingDatesApi = (typeof MissingDatesApi)[keyof typeof MissingDatesApi]
+
+export const MissingDatesApi = {
+ Gap: 'gap',
+ Zero: 'zero',
+} as const
+
export type Operator1Api = (typeof Operator1Api)[keyof typeof Operator1Api]
export const Operator1Api = {
@@ -8456,6 +8463,8 @@ export const BITableCalculationTypeApi = {
export interface BITableCalculationApi {
/** Dimension ID to traverse. Unset chooses the date dimension; 'table' traverses all dimensions. */
computeUsing?: string | null
+ /** Require a complete window of non-null values before displaying a moving average. */
+ requireFullWindow?: boolean | null
type: BITableCalculationTypeApi
/** Number of points, including the current point, in a trailing moving average. */
window?: number | null
@@ -8480,6 +8489,8 @@ export interface BIConfigApi {
dateRange?: DateRangeApi | null
filters: BIFilterApi[]
limit: BIQueryLimitApi
+ /** Fill missing date buckets before table calculations. Unset preserves observed points only. */
+ missingDates?: MissingDatesApi | null
resultFilterGroup?: BIConditionGroupApi | null
resultFilters?: BIResultFilterApi[] | null
rowFilterGroup?: BIConditionGroupApi | null
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index cb2d014503cc..0c9d079e0af2 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -10746,6 +10746,14 @@ export namespace Schemas {
Number50000: 50000,
} as const;
+ export type MissingDates = typeof MissingDates[keyof typeof MissingDates];
+
+
+ export const MissingDates = {
+ Gap: 'gap',
+ Zero: 'zero',
+ } as const;
+
export type Operator1 = typeof Operator1[keyof typeof Operator1];
@@ -10841,6 +10849,8 @@ export namespace Schemas {
export interface BITableCalculation {
/** Dimension ID to traverse. Unset chooses the date dimension; 'table' traverses all dimensions. */
computeUsing?: string | null;
+ /** Require a complete window of non-null values before displaying a moving average. */
+ requireFullWindow?: boolean | null;
type: BITableCalculationType;
/** Number of points, including the current point, in a trailing moving average. */
window?: number | null;
@@ -10865,6 +10875,8 @@ export namespace Schemas {
dateRange?: DateRange | null;
filters: BIFilter[];
limit: BIQueryLimit;
+ /** Fill missing date buckets before table calculations. Unset preserves observed points only. */
+ missingDates?: MissingDates | null;
resultFilterGroup?: BIConditionGroup | null;
resultFilters?: BIResultFilter[] | null;
rowFilterGroup?: BIConditionGroup | null;