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 result drill-down and quick period comparison (#112174)

Marius Andrac1184d8fb3d7
diff --git a/docs/published/handbook/engineering/data-warehouse.md b/docs/published/handbook/engineering/data-warehouse.md
index b52c6fab462a..52b72f0a957f 100644
--- a/docs/published/handbook/engineering/data-warehouse.md
+++ b/docs/published/handbook/engineering/data-warehouse.md
@@ -58,6 +58,10 @@ The **Analysis** card ranks **Top N** categories by a selected measure across th
Each measure's **Format and display** dialog sets its label, currency, decimal precision, abbreviation, percentage format, and suffix. Percentage formatting expects fractional values (0.25 displays as 25%); percent-of-total and percent-change calculations produce that scale automatically. Formats persist in saved insights and apply to charts, tables, and pivot cells. Bar, line, and area charts support a separate series style and left/right axis for each measure. **Combine line + bar** assigns two measures to separate axes with bar and line styles.
+Click a bar, line point, table cell, or pivot cell to explore its source rows. **Filter in new worksheet** preserves the original insight and adds the selected dimensions to a new worksheet. **View underlying rows** loads up to 1,000 matching source rows before aggregation; **Open in SQL editor** carries the same conditions, connection, and effective dashboard filters. Total cells omit rolled-up dimensions, and **Other** selects the categories outside the current Top N. Comparison-period points open rows from their original dates; their filtered-worksheet action is disabled to avoid combining current dates with prior-period conditions. These actions are unavailable on public shared insights.
+
+**Compare previous period** turns date comparison on or off in one click. The adjacent comparison picker still supports custom offsets. Select a bounded date range before enabling comparison.
+
With `SQL_EDITOR_BI_MODE` enabled, open **Business intelligence**, select a table and choose **Add calculated measure** in the data pane.
Enter a name and an aggregate SQL formula, such as `sum(revenue) / nullIf(count(DISTINCT user_id), 0)` for average revenue per user.
Use field names from the selected table. Filters apply before the formula runs for each group on the worksheet.
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 80c0be05f009..3653c943f543 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -9615,53 +9615,65 @@ snapshots:
scenes-app-data-warehouse-settings-schemas--multi-schema--light:
hash: v1.k794b7964.e5d678194a8e191fdf4f8a92cd7328f1e3cb162a81d3c4d05ef608f3c61537da.ZshlecoDn8CpsaVHaONi7UiXq8r-Xi4zJSWKeg7nAP0
scenes-app-data-warehouse-sql-editor--bi-calculated-measure-editor--dark:
- hash: v1.k794b7964.81ba891528e2becb390a17050369aa4aee529e73d832e7aa8df8e254b2e71d5f.Bhs6s6RFn6sHUKJx6Fvo3F8U6FbMW4THtzmK4WtHT9E
+ hash: v1.k794b7964.7c3ba7dcba4d146dcd981b53037f3912d6af86308e5e1adc22a8729a25bcb00d.KfK0rjNQs1Mq4ycTPoMmd69Af-K_70f91oM-rj2yR2M
scenes-app-data-warehouse-sql-editor--bi-calculated-measure-editor--light:
- hash: v1.k794b7964.e7eab764f7313819d189450cbf5162c7af3cd7a55680582b8158476f6b20e385.7v3LE-7zwjRYofqxB0IyvU4bwWTG9bKLribFKclMCMQ
+ hash: v1.k794b7964.91a5ebb4db27dd9ec682f7ecf99ab0fa62f3c7c9c62c1f29dc90896413bf7ced.6QZ4OSvFzyH_FRA43WISTYI1HDdHaw9VGkm06ryuc_g
scenes-app-data-warehouse-sql-editor--bi-combined-measures--dark:
- hash: v1.k794b7964.e8c0f8ac0ea3195c38ce53c88f1208e2af817217e0f9df67320f1c93027020d2.61L-X6HDZNrIyd-_akuzRovJw3w9VQMOLnzRXt2PrYE
+ hash: v1.k794b7964.3a38920408bdcad54bb67ccadc35a6fc89b2fe516b4339ffbb63f317aac2f5a1.u2bU-Axy4V9EsASdg2T5-LqqP6YEBdJSNSk2me6JMzc
scenes-app-data-warehouse-sql-editor--bi-combined-measures--light:
- hash: v1.k794b7964.687437e6bd23fbfb4b07765fa569d170c74d198a89d55caa3c3a937b2b0c75bb.ApzvL75PNdCRmLPnMdskmlsaKVHdWc0Y5v5xjaCTC2A
+ hash: v1.k794b7964.557db2126160c0ba498af0b74177bfbee43479502bb025ee0d32b921dd805bcd.TNR2t8RdGAGKaNmQowUYWEOyoQcpRxvoc7PVO5Fqclo
scenes-app-data-warehouse-sql-editor--bi-connections--dark:
- hash: v1.k794b7964.e52b5d1269e1786a6eacedc31556b27050f1694dbed5cb3cda15ce2331f7449b.aOEAw3DyDPznPADiWToT8EhBgGR_dt1-yC4-HKn5Rto
+ hash: v1.k794b7964.9fcea0d34fd79cc6b33f8fa0e792c8990ef34c56d7fdfba7303035575cfdb268.P74p6-CDSoGcMh8upU1F3MOK7t5mVR4PTd6-YWQBFYQ
scenes-app-data-warehouse-sql-editor--bi-connections--light:
- hash: v1.k794b7964.719217a1104503903f8fb6977e46bffb2722d4e182b2fd09d25f68b94e7f1da9.3YBwf2HMyIwtVJNwzp71QFWK3SrG9mwblddKNeaBanw
+ hash: v1.k794b7964.20a68b6198c6767622ddb244357e383b4e8cfd44c64decc8df41c2ca0f089c38.h1KBSYF8UcP8ih2AiSnzMfz7QUneRw7kJZJe7O6fPdM
scenes-app-data-warehouse-sql-editor--bi-data-source-picker--dark:
- hash: v1.k794b7964.5112f01cd2488a9f09dd693d670514dbdc7ab4bf9edf8f2fb4af53d380b1cf93.VmnAkiYRLVeDIeGQ-Wr2CkM1sy8q7RLhLa5_AzY2ddo
+ hash: v1.k794b7964.ddda7e3729ba2d0ba078ceceee1e8ef44308224557dd3bd2ac4883c3454c6800.NFaSC9E62GVTwg1gtlF-F_pTLx5JnxIqFn-8bkRDLc4
scenes-app-data-warehouse-sql-editor--bi-data-source-picker--light:
- hash: v1.k794b7964.d090b517f5caab086ca573e1a726d4b7fe089809d5deae200e8ece29cfc721e8.uhxw2ZyHQM_eSxRGRTdQIhEv5ZE9igejU5L8BKh0BQA
+ hash: v1.k794b7964.1583664cd6af59ea5d5f9278c943991856499b8362566f856e26ac3f8d344f90.YTsTB6R6yQBWYh89IBP_k5i58-89BUe5p6JWzhCaxjU
+ scenes-app-data-warehouse-sql-editor--bi-drilldown--dark:
+ hash: v1.k794b7964.f2136bea04124e6bdbd3c8a4d2a3f70f97d2879fe7667fd4e5962efcaacfdc05.2CNPSrJj5b4lqDZIxwSokN_sFJXR6C8ziy0Rl2xpGuo
+ scenes-app-data-warehouse-sql-editor--bi-drilldown--light:
+ hash: v1.k794b7964.b2962038ca77a8ddd65b40cd1c76c8927e81618cb27d8f78c670d15d5ca04939.seBfLDk8Ye2L-u6RZuiiIOeDBPTPbKKD2Cu_51qQOU0
scenes-app-data-warehouse-sql-editor--bi-edit-saved-insight--dark:
- hash: v1.k794b7964.8c0bfb93ae442e24a77ac4f865d920c587f4c9087032cd7ba5638df1968dbb66.ZdyxlLypLA7jKpbXMRzXmI14-qXNO3wQb0g8SXeg5z8
+ hash: v1.k794b7964.2d718ad3e78bc2d0f1bbc83351522d5b55036a9fa1073fe6a5a8ca1bfe8e65e9.KU5IvJLSvc0J-4bXkCemSuxmC2mssmt7Vteqa95s4Ck
scenes-app-data-warehouse-sql-editor--bi-edit-saved-insight--light:
- hash: v1.k794b7964.13744c44567b0cf89d5e8157e95d7da4cbe9b86c4c1d895b3ac4bc7761f88fc2.JJBXvK5Br0wLne0_a6qf5tAPG1GE2XZ2TVW0iiI86NY
+ hash: v1.k794b7964.f7f333660f184f6fcdd924fcb44658b15fe395cfb9dac95dc9ef3283cfb5b868.1rCp3Jopv0g8mLCB0iF2BBEPQT90mnAq1_362nfWm0I
scenes-app-data-warehouse-sql-editor--bi-empty-worksheet--dark:
- hash: v1.k794b7964.3b20f018c13b2df3cea913d996e05b2233d28ae85f4293233dc74f2f112e2710.-UEiBxfiTSb_fN2SiUTLj1jAEEXR0eAbpda4Dp2Zluk
+ hash: v1.k794b7964.92adfb0fc582b1ab9f5cc7f555aca5285dc83856e742dc86ad2eaeccabe0f50c.W5selydW_8DrKtNkrMSZHhbewjcFsYATK6_B-3xDtiU
scenes-app-data-warehouse-sql-editor--bi-empty-worksheet--light:
- hash: v1.k794b7964.4339d48fbc96a0cd5d68006f2e9357722eeaf745a97ff2b1617dd14f5c05c4c7.tTXtWEaRb4Bbi1vJC2zMYbckBPgnMjSJMdV64h8B-ys
+ hash: v1.k794b7964.d27ac19fe4fed3f77aad73841d8736c4428638f3ad9db52b95ca5246bd37f307.UoFrAteHqLpRMNjUCq_R2wiTsq8xXxVsggmwhYJvbxw
scenes-app-data-warehouse-sql-editor--bi-measure-display--dark:
- hash: v1.k794b7964.dd90a24acac70ad8ee685e4ad2521e37d23c69a6dbcc9a1e1b696ea77c51d034.lWBoVqwpe7jDa7-IOHdkWUcYVbBgAAitJYz9TFnaGwI
+ hash: v1.k794b7964.a1221958b54ce4c01db587fcebaaa881afc48770e7ea7296ae541e6fbc92ddb6.RlaaoGK24OkRQgxMFHNUGVNHIBkjyuJG3Q-PDm5O_P0
scenes-app-data-warehouse-sql-editor--bi-measure-display--light:
- hash: v1.k794b7964.2ff15d36cb4f2106a0e528080c635952219fa2e115de8923f8e4e0664dc76234.KTnqmR46v9h4nWiLxhdGPC4IU85l5KPqA4jQwNx8228
+ hash: v1.k794b7964.be079b47569b27bdaf21d949cf933cf4b928b98445c42f122c7037f73a589289.oW2_9vZ_t3wsfLDmumhINHXqdX3_eyR0Ii_qrLzsCpg
scenes-app-data-warehouse-sql-editor--bi-mode-worksheet--dark:
- hash: v1.k794b7964.16c0c122bb914a614cd169ddffb2819b3eea5ba28eb7ccad9f575d5cc9f537a2.btA6LlnrotvSwHvc52DonluWpuxhg1rpELuhFTmbiPI
+ hash: v1.k794b7964.d330d306f20cfb0e28a0500acd1fb4465a008253331d43d2bbd1f2c97889297d.lqlokEcTAacUXsHHj_OSXjX9aMDp9aO-mxWRkxTxrQY
scenes-app-data-warehouse-sql-editor--bi-mode-worksheet--light:
- hash: v1.k794b7964.45bb354bd83da54374b512d95ad010a669f6da7172235c539a96f79008dd6700.90jcwEUp8a1IBXAuu9svZJvP_OgmF80woqyqoM6Z9_0
+ hash: v1.k794b7964.fad1891ce712b8a7a874ba32bdf4af29ae84e1f925dcdce7a9283ee3c31885e8.sYCeB2dWDEjpJf8VSU-Jx7ft0G2b37l9eFJVreOajck
+ scenes-app-data-warehouse-sql-editor--bi-one-click-comparison--dark:
+ hash: v1.k794b7964.a8dbe9e2e507ec626b4ff1f18850a01b015be95b62349fa9a6fe2a1b02153980.A0D-4fqdTvQmxbO_kCbKFUu-8UaWiX-ak_rCDRAdAWc
+ scenes-app-data-warehouse-sql-editor--bi-one-click-comparison--light:
+ hash: v1.k794b7964.3d945861e6339b230514c51d4b2549566dfe8fa2dd2678d4e7020b9247a560e2.qDrXX6M4_NFq_J7VgYVhI6eD1JEX6F9FxcSGuUn_zYc
+ scenes-app-data-warehouse-sql-editor--bi-pivot-totals--dark:
+ hash: v1.k794b7964.74cef18a143519eaa371fea91bc4be1b0fc5647c3161556aaa41f576f186a747.5_iW8qxrxcpAQZZInTyCl9XhLU3LJrxZV5E7kCSNpXk
+ scenes-app-data-warehouse-sql-editor--bi-pivot-totals--light:
+ hash: v1.k794b7964.2733d179d4909e31ec6a5630ad3d7a305b2b42cec4b86f8d40f997f378925776.0iUITJatGLxmVF9lwIt_DPQIUavWAHD52P29VB87kqA
scenes-app-data-warehouse-sql-editor--bi-quick-filters--dark:
- hash: v1.k794b7964.fe7ad7f2476a65e33dd1f1eb0a61b07901ebf687c7ffc207651ee882a1ef9329.3cPSfmfMF8ORm9g8t7K3EuvKTbSZ0KXsHOSemHB8amA
+ hash: v1.k794b7964.40c7de78318903590991f629a9fca827e2203b11ac5259fc82d87410873238da.P1JE_MI9SEW2KXQ-6O2t9bPaaDTq0D8CCoDKJuwzYFc
scenes-app-data-warehouse-sql-editor--bi-quick-filters--light:
- hash: v1.k794b7964.aa217097678c2d9608b30fc7b475c0e615f7b8f696acad4d61a1b8a4a8928458.cyjC8n37gvu4xZCY2b7EYVLL1tWWCfr2EEz421zK0yY
+ hash: v1.k794b7964.2b7060f2d34fcbe8189c7dc92d92a7c51cded35310406e08f93af204ea26e8b2.hKo9Das8GnSK2XMQ3s-lTQtTDaPEraIyp1Da_GUSZJY
scenes-app-data-warehouse-sql-editor--bi-quick-filters-narrow--dark:
- hash: v1.k794b7964.969f9230dbdd7b5c733d03a05911324410e950bf7c914c9bbe38aae22cfb7397.oDf2f_pKbgkrN2OccE2ZyK3bJFksS3JMRESZv3bQxi4
+ hash: v1.k794b7964.06c1b8aa2a1d5a7ee7cc9175280da635552884f8337d47c4ad8e78cdf5dc5d60.wwx8fbd3OYzMNuewloPd5guoMw2BXj2otqGzoHDyo8E
scenes-app-data-warehouse-sql-editor--bi-quick-filters-narrow--light:
- hash: v1.k794b7964.7fed5a95aceebadc02c6bbbc732ce48f5aa60068ed2048234323a64c9946f793.zmyDn0HjAYc3jAUeu7dtCyiwgU3HnEJA4c4eH7hlWpg
+ hash: v1.k794b7964.759dd0ef5d49d64bd54fb44db6ad4a3ac98382899d8d1a6040fda5806f127046.p2EBmtbQy4RIEWVzIY2EwiILDHNkl709wXqywY4iKJ8
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.c0479ed572a18dc847b51fbec7a001ca174612ce01e3823f75152166675c5286.-8HnSBQkNsY-ie-KIFK-J7mm_FsbCqMnw3sHZTYj5MQ
+ hash: v1.k794b7964.d1cc2a4ae330f387811b9d8a8d2cf05d56cf8b892f659842744d96a1fd2264b7.7JOnlLtpbcyAhaV7dxQSkAd2Jm-gu4WU5SMcoUaYqu4
scenes-app-data-warehouse-sql-editor--bi-table-analysis--light:
- hash: v1.k794b7964.eeafc7a295497fcd29ca4e3222bd912c715edf25f0c39201db78c75af48d81ff.2z4eTqDCl2u4WVezL8PnqAKL5NjxLEujQBmMf9nWQms
+ hash: v1.k794b7964.bc71202ae57c32756e4de35d4b3da9393929a3dce12c8045c9f936d6b96f8529._kezl7FyW1-gI5_iKKy3U6a1B_RdZcaNwgC9QdM_qNM
scenes-app-data-warehouse-sql-editor--edited-insight--dark:
hash: v1.k794b7964.334b216a8359c768613cdec5b99a8a8ee26b6b5fac76397eaed8d6d1401a23c0.0pI7NMTufzUIfDel9Ngmhv3P3sdBu6IgpSj5xYNmYrY
scenes-app-data-warehouse-sql-editor--edited-insight--light:
diff --git a/frontend/src/queries/Query/Query.tsx b/frontend/src/queries/Query/Query.tsx
index 0f23d867cdeb..c22fe318b240 100644
--- a/frontend/src/queries/Query/Query.tsx
+++ b/frontend/src/queries/Query/Query.tsx
@@ -152,6 +152,7 @@ export function Query<Q extends Node>(props: QueryProps<Q>): JSX.Element | null
embedded={embedded}
inSharedMode={inSharedMode}
editMode={!!editMode}
+ filtersOverride={filtersOverride}
variablesOverride={props.variablesOverride}
/>
)
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlBarGraph.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlBarGraph.tsx
index c9b376ccae16..63b6857f7b37 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlBarGraph.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlBarGraph.tsx
@@ -17,6 +17,7 @@ import { ChartDisplayType } from '~/types'
import { makeChartErrorHandler } from 'products/product_analytics/frontend/insights/trends/shared/chartErrorHandler'
import { type SqlChartProps } from './SqlChart'
+import { SqlChartTooltip } from './SqlChartTooltip'
import {
type SqlBarGraphConfig,
type SqlLineSeriesMeta,
@@ -68,6 +69,18 @@ export const SqlBarGraph = (props: SqlChartProps): JSX.Element => {
theme={model.theme}
config={model.config}
onPointClick={onPointClickProp ? onPointClick : undefined}
+ tooltip={
+ onPointClickProp
+ ? (context) => (
+ <SqlChartTooltip
+ context={context}
+ config={model.config.tooltip}
+ onPointClick={onPointClickProp}
+ hint={props.pointClickHint}
+ />
+ )
+ : undefined
+ }
onError={handleChartError}
>
<ReferenceLines lines={model.config.referenceLines ?? []} />
@@ -80,6 +93,18 @@ export const SqlBarGraph = (props: SqlChartProps): JSX.Element => {
theme={model.theme}
config={model.config}
onPointClick={onPointClickProp ? onPointClick : undefined}
+ tooltip={
+ onPointClickProp
+ ? (context) => (
+ <SqlChartTooltip
+ context={context}
+ config={model.config.tooltip}
+ onPointClick={onPointClickProp}
+ hint={props.pointClickHint}
+ />
+ )
+ : undefined
+ }
onError={handleChartError}
>
{props.showAnnotations && props.insightNumericId && (
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlChart.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlChart.tsx
index 21e6079e5f7a..f15f6daadeef 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlChart.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlChart.tsx
@@ -34,6 +34,7 @@ export type SqlChartProps = {
/** Called when the user clicks a data point. Receives the series key, x-axis index, and label.
* When provided, the SQL chart shows a "click to inspect" hint in the tooltip. */
onPointClick?: (seriesKey: string, dataIndex: number, label: string) => void
+ pointClickHint?: string
}
/**
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlChartTooltip.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlChartTooltip.tsx
new file mode 100644
index 000000000000..10adc6ec68a9
--- /dev/null
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlChartTooltip.tsx
@@ -0,0 +1,34 @@
+import { DefaultTooltip, TooltipConfig, TooltipContext } from '@posthog/quill-charts'
+
+import { SqlChartProps } from './SqlChart'
+import { SqlLineSeriesMeta, formatSqlSeriesValue } from './sqlLineGraphAdapter'
+
+export function SqlChartTooltip({
+ context,
+ config,
+ onPointClick,
+ hint,
+}: {
+ context: TooltipContext<SqlLineSeriesMeta>
+ config?: TooltipConfig
+ onPointClick: NonNullable<SqlChartProps['onPointClick']>
+ hint?: string
+}): JSX.Element {
+ return (
+ <DefaultTooltip
+ {...context}
+ valueFormatter={
+ config?.valueFormatter ?? ((value, entry) => formatSqlSeriesValue(value, entry.series.meta?.settings))
+ }
+ labelFormatter={config?.labelFormatter}
+ showTotal={config?.showTotal}
+ totalFormatter={config?.totalFormatter}
+ sortedByValue
+ footer={hint ?? 'Click a series to inspect'}
+ onRowClick={(entry) => {
+ context.onUnpin?.()
+ onPointClick(entry.series.key, context.dataIndex, context.label)
+ }}
+ />
+ )
+}
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlComboGraph.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlComboGraph.tsx
index d2fd3ce1163d..2d076a8f709f 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlComboGraph.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlComboGraph.tsx
@@ -1,12 +1,13 @@
import clsx from 'clsx'
-import { TimeSeriesComboChart } from '@posthog/quill-charts'
+import { TimeSeriesComboChart, type PointClickData } from '@posthog/quill-charts'
import { AnnotationsLayer } from 'lib/components/AnnotationsOverlay/AnnotationsLayer'
import { makeChartErrorHandler } from 'products/product_analytics/frontend/insights/trends/shared/chartErrorHandler'
import { type SqlChartProps } from './SqlChart'
+import { SqlChartTooltip } from './SqlChartTooltip'
import { SqlLineSeriesMeta, buildComboChartConfig } from './sqlLineGraphAdapter'
import { useSqlChartModel } from './useSqlChartModel'
@@ -36,6 +37,24 @@ export const SqlComboGraph = (props: SqlChartProps): JSX.Element => {
theme={model.theme}
config={model.config}
onError={handleChartError}
+ tooltip={
+ props.onPointClick
+ ? (context) => (
+ <SqlChartTooltip
+ context={context}
+ config={model.config.tooltip}
+ onPointClick={props.onPointClick!}
+ hint={props.pointClickHint}
+ />
+ )
+ : undefined
+ }
+ onPointClick={
+ props.onPointClick
+ ? (data: PointClickData<SqlLineSeriesMeta>) =>
+ props.onPointClick?.(data.series.key, data.dataIndex, data.label)
+ : undefined
+ }
>
{props.showAnnotations && props.insightNumericId && (
<AnnotationsLayer insightNumericId={props.insightNumericId} dates={model.labels} />
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlLineGraph.test.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlLineGraph.test.tsx
index be122a24d68f..c97b8db7c1ce 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlLineGraph.test.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlLineGraph.test.tsx
@@ -19,7 +19,9 @@ import { buildAnnotation } from '~/test/insight-testing/test-data'
import { AnnotationScope, ChartDisplayType } from '~/types'
import { AxisSeries } from '../../dataVisualizationLogic'
+import { SqlBarGraph } from './SqlBarGraph'
import { SqlChartProps } from './SqlChart'
+import { SqlComboGraph } from './SqlComboGraph'
import { SqlLineGraph } from './SqlLineGraph'
// Some blocks below mount the full DataVisualization tree (~7 logics). Neither timeout is set
@@ -84,7 +86,34 @@ const renderChart = async (overrides: Partial<SqlChartProps>): Promise<void> =>
const lowestTick = (ticks: string[]): number => Math.min(...ticks.map((t) => parseFloat(t.replace(/[^0-9.eE+-]/g, ''))))
-// Full-mount helpers: drive a real SQL insight (VisualizationNode) through the
+it.each([
+ { name: 'line', Component: SqlLineGraph },
+ { name: 'bar', Component: SqlBarGraph },
+ { name: 'combo', Component: SqlComboGraph },
+])('drills into the selected pinned tooltip series on a $name chart', async ({ Component }) => {
+ const onPointClick = jest.fn()
+ renderWithInsights({
+ component: (
+ <Component
+ {...props({
+ yData: [
+ ySeries('a', [10, 20, 30], { display: { displayType: 'bar' } }),
+ ySeries('b', [100, 200, 300], { display: { displayType: 'line' } }),
+ ],
+ onPointClick,
+ })}
+ />
+ ),
+ })
+ await screen.findByLabelText(/chart with 2 data series/i)
+ await sqlChart.hoverTooltip(1, 3)
+ fireEvent.click(getHogChart().element)
+ fireEvent.click(screen.getByText('b', { selector: '[data-attr="hog-chart-tooltip-series"]' }))
+ expect(onPointClick).toHaveBeenCalledWith('b-1', 1, 'Tue')
+ expect(onPointClick).toHaveBeenCalledTimes(1)
+})
+
+// Full-mount helpers: drive a real SQL insight (DataVisualizationNode) through the
// DataVisualization tree. Used for tooltip / legend / overlay behavior that depends on the live
// render path, with the query result injected via cachedResults (no network).
function lineFixture(columns: { name: string; type?: string; valueAt: (i: number) => unknown }[]): DataVizFixture {
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlLineGraph.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlLineGraph.tsx
index 8ba0a9140dcb..06a20beb01b1 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlLineGraph.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/SqlLineGraph.tsx
@@ -1,14 +1,15 @@
import clsx from 'clsx'
import { useCallback } from 'react'
-import { DefaultTooltip, TimeSeriesLineChart, type PointClickData, type TooltipContext } from '@posthog/quill-charts'
+import { TimeSeriesLineChart, type PointClickData, type TooltipContext } from '@posthog/quill-charts'
import { AnnotationsLayer } from 'lib/components/AnnotationsOverlay/AnnotationsLayer'
import { makeChartErrorHandler } from 'products/product_analytics/frontend/insights/trends/shared/chartErrorHandler'
import { type SqlChartProps } from './SqlChart'
-import { SqlLineSeriesMeta, buildLineChartConfig, formatSqlSeriesValue } from './sqlLineGraphAdapter'
+import { SqlChartTooltip } from './SqlChartTooltip'
+import { SqlLineSeriesMeta, buildLineChartConfig } from './sqlLineGraphAdapter'
import { useSqlChartModel } from './useSqlChartModel'
const handleChartError = makeChartErrorHandler('sql-line-chart')
@@ -35,27 +36,19 @@ export const SqlLineGraph = (props: SqlChartProps): JSX.Element => {
// avoid duplicating the per-column formatting logic.
const renderTooltip = useCallback(
(ctx: TooltipContext<SqlLineSeriesMeta>) => {
- if (!model) {
+ if (!model || !onPointClickProp) {
return null
}
- const { valueFormatter, labelFormatter, showTotal, totalFormatter } = model.config.tooltip ?? {}
return (
- <DefaultTooltip
- {...ctx}
- valueFormatter={
- valueFormatter ??
- ((value, entry) =>
- formatSqlSeriesValue(value, (entry.series.meta as SqlLineSeriesMeta | undefined)?.settings))
- }
- labelFormatter={labelFormatter}
- showTotal={showTotal}
- totalFormatter={totalFormatter}
- sortedByValue
- footer="Click to inspect persons"
+ <SqlChartTooltip
+ context={ctx}
+ config={model.config.tooltip}
+ onPointClick={onPointClickProp}
+ hint={props.pointClickHint ?? 'Click to inspect persons'}
/>
)
},
- [model]
+ [model, onPointClickProp, props.pointClickHint]
)
return (
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.ts b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.ts
index 5098135c5519..e5b7d97b4c95 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.ts
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Charts/sqlLineGraphAdapter.ts
@@ -94,7 +94,7 @@ export function hasMixedSeriesTypes(yData: SqlLineYSeries[], visualizationType:
const getSeriesLabel = (series: SqlLineYSeries): string =>
series.settings?.display?.label || ('name' in series ? series.name : series.column.name)
-const getSeriesKey = (series: SqlLineYSeries, index: number): string =>
+export const getSeriesKey = (series: SqlLineYSeries, index: number): string =>
'breakdownValue' in series ? JSON.stringify([series.name, series.breakdownValue]) : `${series.column.name}-${index}`
/** Shares {@link getSeriesKey} with {@link buildSeries} so each trend line's `seriesKey` matches its source series. */
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Heatmap/TwoDimensionalHeatmap.test.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Heatmap/TwoDimensionalHeatmap.test.tsx
index 673ba26b98a3..f92b24e3584b 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Heatmap/TwoDimensionalHeatmap.test.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Heatmap/TwoDimensionalHeatmap.test.tsx
@@ -1,6 +1,6 @@
import '@testing-library/jest-dom'
-import { act, cleanup, render, screen } from '@testing-library/react'
+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
import { BindLogic, Provider } from 'kea'
import { VisualizationNode, NodeKind } from '~/queries/schema/schema-general'
@@ -56,7 +56,8 @@ const response = {
const setup = (
nullLabel = '(header null)',
nullValue = '',
- responseOverride: typeof response = response
+ responseOverride: typeof response = response,
+ onInspect?: (record: Record<string, unknown>) => void
): ReturnType<typeof dataVisualizationLogic.build> => {
logicCounter += 1
const testKey = `test-two-dimensional-heatmap-${logicCounter}`
@@ -74,7 +75,7 @@ const setup = (
render(
<Provider>
<BindLogic logic={dataVisualizationLogic} props={props}>
- <TwoDimensionalHeatmap />
+ <TwoDimensionalHeatmap onInspect={onInspect} />
</BindLogic>
</Provider>
)
@@ -83,6 +84,25 @@ const setup = (
}
describe('TwoDimensionalHeatmap', () => {
+ it('keeps null and literal labels separately inspectable even when display labels collide', async () => {
+ const onInspect = jest.fn()
+ const values = [null, 'null', 'null (2)', '']
+ setup(
+ 'null',
+ '',
+ {
+ ...response,
+ results: values.map((value, index) => [value, 'Enterprise', index + 10]),
+ },
+ onInspect
+ )
+
+ for (const [index, value] of values.entries()) {
+ fireEvent.click((await screen.findByText(String(index + 10))).closest('button')!)
+ expect(onInspect).toHaveBeenLastCalledWith({ region: value, segment: 'Enterprise', count: index + 10 })
+ }
+ expect(screen.queryByText(/duplicate/)).not.toBeInTheDocument()
+ })
afterEach(() => {
cleanup()
// Guard against any pollution leaking into other tests if a regression reintroduces it
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Heatmap/TwoDimensionalHeatmap.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Heatmap/TwoDimensionalHeatmap.tsx
index b015e91f964a..bea50ddb0695 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Heatmap/TwoDimensionalHeatmap.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Heatmap/TwoDimensionalHeatmap.tsx
@@ -2,13 +2,13 @@ import clsx from 'clsx'
import { useActions, useValues } from 'kea'
import { useEffect, useMemo } from 'react'
-import { LemonBanner } from '@posthog/lemon-ui'
+import { LemonBanner, LemonButton } from '@posthog/lemon-ui'
import type { Sorting } from 'lib/lemon-ui/LemonTable/sorting'
import { SortingIndicator, getNextSorting } from 'lib/lemon-ui/LemonTable/sorting'
import { InsightEmptyState } from 'scenes/insights/EmptyStates'
-import { HeatmapSettings } from '~/queries/schema/schema-general'
+import { HeatmapSettings, NodeKind } from '~/queries/schema/schema-general'
import { getContrastingTextClass } from '../../colorUtils'
import { dataVisualizationLogic, formatDataWithSettings } from '../../dataVisualizationLogic'
@@ -23,6 +23,7 @@ import {
stretchGradientStopsToValues,
} from './heatmapUtils'
import {
+ getDistinctHeatmapLabels,
getHeatmapSettingsWithSorting,
getSortingFromHeatmapSettings,
HEATMAP_ROW_LABEL_SORT_KEY,
@@ -61,7 +62,8 @@ type HeatmapDataSettings = Pick<
const buildHeatmapData = (
rows: any[],
heatmapSettings: HeatmapDataSettings,
- columnIndexes: Record<string, number>
+ columnIndexes: Record<string, number>,
+ axisLabels?: { x: Map<unknown, string>; y: Map<unknown, string> }
): HeatmapData => {
const xValues: string[] = []
const yValues: string[] = []
@@ -92,8 +94,8 @@ const buildHeatmapData = (
const nullLabel = getHeatmapNullLabel(heatmapSettings)
rows.forEach((row) => {
- const xLabel = formatHeatmapLabel(row[xIndex], nullLabel)
- const yLabel = formatHeatmapLabel(row[yIndex], nullLabel)
+ const xLabel = axisLabels?.x.get(row[xIndex]) ?? formatHeatmapLabel(row[xIndex], nullLabel)
+ const yLabel = axisLabels?.y.get(row[yIndex]) ?? formatHeatmapLabel(row[yIndex], nullLabel)
const numericValue = parseNumericValue(row[valueIndex])
if (!xIndexMap.has(xLabel)) {
@@ -110,7 +112,7 @@ const buildHeatmapData = (
cellValues[yLabel] = Object.create(null)
}
- const cellKey = `${yLabel}||${xLabel}`
+ const cellKey = JSON.stringify([yLabel, xLabel])
if (seenCells.has(cellKey)) {
duplicateCellCount += 1
}
@@ -162,8 +164,14 @@ const getNextSortingTitle = (currentSorting: Sorting | null, columnKey: string,
return `Click to sort rows ${nextSorting.order === 1 ? 'ascending' : 'descending'}`
}
-export function TwoDimensionalHeatmap({ allowSorting = true }: { allowSorting?: boolean }): JSX.Element {
- const { response, columns, chartSettings } = useValues(dataVisualizationLogic)
+export function TwoDimensionalHeatmap({
+ allowSorting = true,
+ onInspect,
+}: {
+ allowSorting?: boolean
+ onInspect?: (record: Record<string, unknown>) => void
+}): JSX.Element {
+ const { response, columns, chartSettings, query } = useValues(dataVisualizationLogic)
const { updateChartSettings } = useActions(dataVisualizationLogic)
const heatmapSettings = chartSettings.heatmap ?? {}
@@ -185,6 +193,35 @@ export function TwoDimensionalHeatmap({ allowSorting = true }: { allowSorting?:
{} as Record<string, number>
)
}, [columns])
+ const axisLabels = useMemo(
+ () =>
+ (onInspect || query.kind === NodeKind.BIVisualizationNode) && xAxisColumn && yAxisColumn
+ ? {
+ x: getDistinctHeatmapLabels(
+ rows.map((row: unknown[]) => row[columnIndexes[xAxisColumn]]),
+ getHeatmapNullLabel(heatmapSettings)
+ ),
+ y: getDistinctHeatmapLabels(
+ rows.map((row: unknown[]) => row[columnIndexes[yAxisColumn]]),
+ getHeatmapNullLabel(heatmapSettings)
+ ),
+ }
+ : undefined,
+ [rows, columnIndexes, xAxisColumn, yAxisColumn, heatmapSettings, onInspect, query.kind]
+ )
+ const sourceRowsByCell = useMemo(() => {
+ const cells = new Map<string, unknown[] | null>()
+ if (onInspect && xAxisColumn && yAxisColumn) {
+ for (const row of rows) {
+ const key = JSON.stringify([
+ axisLabels?.x.get(row[columnIndexes[xAxisColumn]]),
+ axisLabels?.y.get(row[columnIndexes[yAxisColumn]]),
+ ])
+ cells.set(key, cells.has(key) ? null : row)
+ }
+ }
+ return cells
+ }, [rows, columnIndexes, xAxisColumn, yAxisColumn, axisLabels, onInspect])
const hasSelection = selectedColumns.every(Boolean)
const hasValidColumns = selectedColumns.every((columnName) => {
@@ -206,7 +243,12 @@ export function TwoDimensionalHeatmap({ allowSorting = true }: { allowSorting?:
}
}
- return buildHeatmapData(rows, { xAxisColumn, yAxisColumn, valueColumn, nullLabel, nullValue }, columnIndexes)
+ return buildHeatmapData(
+ rows,
+ { xAxisColumn, yAxisColumn, valueColumn, nullLabel, nullValue },
+ columnIndexes,
+ axisLabels
+ )
}, [
rows,
hasSelection,
@@ -217,6 +259,7 @@ export function TwoDimensionalHeatmap({ allowSorting = true }: { allowSorting?:
nullLabel,
nullValue,
columnIndexes,
+ axisLabels,
])
useEffect(() => {
@@ -379,6 +422,17 @@ export function TwoDimensionalHeatmap({ allowSorting = true }: { allowSorting?:
cellValue === null
? 'transparent'
: interpolateHeatmapColor(cellValue, scaledGradientStops)
+ const formattedValue =
+ typeof cellValue === 'number' && valueSettings
+ ? String(
+ formatDataWithSettings(
+ cellValue *
+ (valueSettings.formatting?.style === 'percent' ? 100 : 1),
+ valueSettings
+ )
+ )
+ : formatHeatmapValue(cellValue, nullValueDisplay)
+ const sourceRow = sourceRowsByCell.get(JSON.stringify([xValue, yValue]))
return (
<td
@@ -389,15 +443,28 @@ export function TwoDimensionalHeatmap({ allowSorting = true }: { allowSorting?:
)}
style={{ backgroundColor: cellColor }}
>
- {typeof cellValue === 'number' && valueSettings
- ? String(
- formatDataWithSettings(
- cellValue *
- (valueSettings.formatting?.style === 'percent' ? 100 : 1),
- valueSettings
- )
- )
- : formatHeatmapValue(cellValue, nullValueDisplay)}
+ {onInspect && sourceRow ? (
+ <LemonButton
+ type="tertiary"
+ size="xsmall"
+ className="w-full justify-center !text-inherit"
+ tooltip="Explore this result"
+ onClick={() =>
+ onInspect(
+ Object.fromEntries(
+ columns.map((column) => [
+ column.name,
+ sourceRow[column.dataIndex],
+ ])
+ )
+ )
+ }
+ >
+ {formattedValue}
+ </LemonButton>
+ ) : (
+ formattedValue
+ )}
</td>
)
})}
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Heatmap/twoDimensionalHeatmapUtils.ts b/frontend/src/queries/nodes/DataVisualization/Components/Heatmap/twoDimensionalHeatmapUtils.ts
index a17b8a677e9d..f0cb8a88dee0 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Heatmap/twoDimensionalHeatmapUtils.ts
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Heatmap/twoDimensionalHeatmapUtils.ts
@@ -6,6 +6,29 @@ export const HEATMAP_ROW_LABEL_SORT_KEY = '__heatmap_row_label__'
export type HeatmapCellValues = Record<string, Record<string, number | null>>
+export function getDistinctHeatmapLabels(values: unknown[], nullLabel: string): Map<unknown, string> {
+ const labels = new Map<unknown, string>()
+ const reserved = new Set(values.map((value) => String(value ?? nullLabel)))
+ const used = new Set<string>()
+ for (const value of values) {
+ if (labels.has(value)) {
+ continue
+ }
+ const base = String(value ?? nullLabel)
+ let label = base
+ let suffix = 2
+ while (used.has(label)) {
+ label = `${base} (${suffix++})`
+ while (reserved.has(label)) {
+ label = `${base} (${suffix++})`
+ }
+ }
+ labels.set(value, label)
+ used.add(label)
+ }
+ return labels
+}
+
const compareHeatmapLabels = (left: string, right: string): number =>
left.localeCompare(right, undefined, { numeric: true, sensitivity: 'base' })
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Table.tsx b/frontend/src/queries/nodes/DataVisualization/Components/Table.tsx
index 513f63a25d5b..2982a194162f 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Table.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Table.tsx
@@ -5,7 +5,7 @@ import posthog from 'posthog-js'
import React, { useCallback, useLayoutEffect, useRef, useState } from 'react'
import { IconPin, IconPinFilled } from '@posthog/icons'
-import { LemonBanner, LemonTable, LemonTableColumn, Tooltip } from '@posthog/lemon-ui'
+import { LemonBanner, LemonButton, LemonTable, LemonTableColumn, Tooltip } from '@posthog/lemon-ui'
import { dayjs } from 'lib/dayjs'
import { lightenDarkenColor } from 'lib/utils/colors'
@@ -28,6 +28,7 @@ interface TableProps {
context: QueryContext<VisualizationNode> | undefined
cachedResults: HogQLQueryResponse | undefined
embedded?: boolean
+ onInspect?: (record: Record<string, unknown>) => void
}
export const DEFAULT_PAGE_SIZE = 500
@@ -154,6 +155,7 @@ export const Table = (props: TableProps): JSX.Element => {
tabularData,
tabularColumns,
sourceTabularColumns,
+ sourceTabularData,
conditionalFormattingRules,
responseLoading,
responseError,
@@ -305,6 +307,31 @@ export const Table = (props: TableProps): JSX.Element => {
)
}
+ if (props.onInspect) {
+ const sourceRow = isTransposed ? sourceTabularData[index - 1] : data
+ const sourceColumns = isTransposed ? sourceTabularColumns : tabularColumns
+ return (
+ <LemonButton
+ type="tertiary"
+ size="xsmall"
+ className="max-w-full !text-inherit"
+ tooltip="Explore this result"
+ onClick={() =>
+ props.onInspect?.(
+ Object.fromEntries(
+ sourceColumns.map((column, index) => [
+ column.column.name,
+ sourceRow[index]?.value,
+ ])
+ )
+ )
+ }
+ >
+ <span className="truncate">{String(cell.formattedValue ?? '—')}</span>
+ </LemonButton>
+ )
+ }
+
return (
<div className="truncate" title={getCellTitle(cell)}>
{renderColumn(
diff --git a/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx b/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx
index 35a06b0fd3b9..0d00f9829e55 100644
--- a/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx
@@ -17,6 +17,7 @@ import { urls } from 'scenes/urls'
import { insightVizDataCollectionId, insightVizDataNodeKey } from '~/queries/nodes/InsightViz/insightVizKeys'
import {
AnyResponseType,
+ DashboardFilter,
VisualizationNode,
HogQLQuery,
HogQLQueryResponse,
@@ -28,6 +29,9 @@ import { shouldQueryBeAsync } from '~/queries/utils'
import { ChartDisplayType, ExportContext, ExporterFormat, InsightLogicProps } from '~/types'
import { alertsToThresholdGoalLines, insightAlertsLogic } from 'products/alerts/frontend/logic/insightAlertsLogic'
+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 { getBIVisualizationSource } from 'products/business_intelligence/frontend/biQueryResults'
import { HogQLBoldNumber } from 'products/product_analytics/frontend/insights/shared/BoldNumber/BoldNumber'
@@ -39,6 +43,7 @@ import { QueryFeature } from '../DataTable/queryFeatures'
import { PieChart } from './Components/Charts/PieChart'
import { SqlBoxPlot } from './Components/Charts/SqlBoxPlot'
import { isSqlChartVisualizationType, SqlChart } from './Components/Charts/SqlChart'
+import { getSeriesKey } from './Components/Charts/sqlLineGraphAdapter'
import { SqlMetricCard } from './Components/Charts/SqlMetricCard'
import { SqlScatterGraph } from './Components/Charts/SqlScatterGraph'
import { TwoDimensionalHeatmap } from './Components/Heatmap/TwoDimensionalHeatmap'
@@ -68,6 +73,7 @@ export interface DataTableVisualizationProps {
inSharedMode?: boolean
exportContext?: ExportContext
/** Dashboard variables to override the ones in the query */
+ filtersOverride?: DashboardFilter | null
variablesOverride?: Record<string, HogQLVariable> | null
/** Attach ourselves to another logic, such as the scene logic */
attachTo?: BuiltLogic | LogicWrapper
@@ -83,6 +89,7 @@ export function DataTableVisualization({
cachedResults,
readOnly,
variablesOverride,
+ filtersOverride,
attachTo,
editMode,
embedded,
@@ -112,7 +119,8 @@ export function DataTableVisualization({
applyDataVisualizationQueryUpdate(queryRef, setter, setQuery)
},
cachedResults,
- variablesOverride,
+ variablesOverride: variablesOverride ?? insightProps.variablesOverride,
+ filtersOverride: filtersOverride ?? insightProps.filtersOverride,
limitContext: context?.limitContext,
}
@@ -122,7 +130,8 @@ export function DataTableVisualization({
cachedResults,
loadPriority: insightProps.loadPriority,
dataNodeCollectionId,
- variablesOverride,
+ variablesOverride: variablesOverride ?? insightProps.variablesOverride,
+ filtersOverride: filtersOverride ?? insightProps.filtersOverride,
limitContext: context?.limitContext,
}
@@ -165,6 +174,8 @@ export function DataTableVisualization({
editMode={editMode}
embedded={embedded}
inSharedMode={inSharedMode}
+ filtersOverride={filtersOverride ?? insightProps.filtersOverride}
+ variablesOverride={variablesOverride ?? insightProps.variablesOverride}
/>
</BindLogic>
</BindLogic>
@@ -197,6 +208,14 @@ function InternalDataTableVisualization(props: DataTableVisualizationProps): JSX
} = useValues(dataVisualizationLogic)
const presetChartHeight = !props.embedded && scenePresetChartHeight
+ const drilldownProps = {
+ key: dataVisualizationProps.key,
+ query,
+ filtersOverride: props.filtersOverride,
+ variablesOverride: props.variablesOverride,
+ }
+ const { inspect } = useActions(biDrilldownLogic(drilldownProps))
+ const canDrill = query.kind === NodeKind.BIVisualizationNode && !props.inSharedMode
const { seriesBreakdownData } = useValues(seriesBreakdownLogic({ key: dataVisualizationProps.key }))
const { goalLines } = useValues(displayLogic)
@@ -263,6 +282,7 @@ function InternalDataTableVisualization(props: DataTableVisualizationProps): JSX
context={props.context}
cachedResults={props.cachedResults as HogQLQueryResponse | undefined}
embedded={props.embedded}
+ onInspect={canDrill ? inspect : undefined}
/>
)
} else if (isSqlChartVisualizationType(effectiveVisualizationType)) {
@@ -282,6 +302,26 @@ function InternalDataTableVisualization(props: DataTableVisualizationProps): JSX
showAnnotations={!props.inSharedMode && isDateXAxis && chartSettings.showAnnotations === true}
presetChartHeight={presetChartHeight}
embedded={props.embedded}
+ onPointClick={
+ canDrill
+ ? (seriesKey, dataIndex) => {
+ const series = _yData.find(
+ (series, index) => getSeriesKey(series, index) === seriesKey
+ )
+ if (_xData) {
+ inspect(
+ getBIChartRecord(
+ query,
+ _xData.column.name,
+ _xData.data[dataIndex],
+ series && 'breakdownValue' in series ? series.breakdownValue : undefined
+ )
+ )
+ }
+ }
+ : undefined
+ }
+ pointClickHint={canDrill ? 'Click a series to explore this result' : undefined}
/>
</BindLogic>
)
@@ -325,7 +365,12 @@ function InternalDataTableVisualization(props: DataTableVisualizationProps): JSX
/>
)
} else if (effectiveVisualizationType === ChartDisplayType.TwoDimensionalHeatmap) {
- component = <TwoDimensionalHeatmap allowSorting={!(props.embedded && readOnly)} />
+ component = (
+ <TwoDimensionalHeatmap
+ allowSorting={!(props.embedded && readOnly)}
+ onInspect={canDrill ? inspect : undefined}
+ />
+ )
} else if (effectiveVisualizationType === ChartDisplayType.BoldNumber) {
component = <HogQLBoldNumber />
} else if (effectiveVisualizationType === ChartDisplayType.Metric) {
@@ -339,6 +384,24 @@ function InternalDataTableVisualization(props: DataTableVisualizationProps): JSX
)
}
+ if (query.kind === NodeKind.BIVisualizationNode) {
+ component = (
+ <>
+ {seriesBreakdownData.warning ? (
+ <LemonBanner type="info">{seriesBreakdownData.warning}</LemonBanner>
+ ) : 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.
+ </LemonBanner>
+ ) : null}
+ {component}
+ {canDrill ? <BIDrilldownModal logicProps={drilldownProps} /> : null}
+ </>
+ )
+ }
+
if (props.embedded) {
return (
<div
@@ -359,16 +422,6 @@ function InternalDataTableVisualization(props: DataTableVisualizationProps): JSX
})}
>
<div className="relative w-full flex flex-col gap-4 flex-1 overflow-hidden">
- {query.kind === NodeKind.BIVisualizationNode &&
- !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.
- </LemonBanner>
- ) : null}
{!readOnly && showResultControls && (
<>
<LemonDivider className="my-0" />
diff --git a/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.ts b/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.ts
index 9b247a418ff1..92e15fb23668 100644
--- a/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.ts
+++ b/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.ts
@@ -38,6 +38,7 @@ import {
ChartSettings,
ChartSettingsDisplay,
ChartSettingsFormatting,
+ DashboardFilter,
ConditionalFormattingRule,
VisualizationNode,
HeatmapSettings,
@@ -124,6 +125,7 @@ export interface DataVisualizationLogicProps {
loadPriority?: number
/** Dashboard variables to override the ones in the query */
variablesOverride?: Record<string, HogQLVariable> | null
+ filtersOverride?: DashboardFilter | null
limitContext?: 'posthog_ai'
}
@@ -957,6 +959,7 @@ export const dataVisualizationLogic = kea<dataVisualizationLogicType>([
dataNodeCollectionId: props.dataNodeCollectionId,
loadPriority: props.loadPriority,
variablesOverride: props.variablesOverride,
+ filtersOverride: props.filtersOverride,
limitContext: props.limitContext,
}),
[
@@ -979,6 +982,7 @@ export const dataVisualizationLogic = kea<dataVisualizationLogicType>([
dataNodeCollectionId: props.dataNodeCollectionId,
loadPriority: props.loadPriority,
variablesOverride: props.variablesOverride,
+ filtersOverride: props.filtersOverride,
limitContext: props.limitContext,
}),
['loadData'],
diff --git a/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx b/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx
index 643d02cc02be..9cda8c1c9697 100644
--- a/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx
@@ -1264,3 +1264,129 @@ export const BIMeasureDisplay: Story = {
await userEvent.click((await within(canvasElement).findAllByRole('button', { name: 'Format and display' }))[0])
},
}
+
+export const BIDrilldown: Story = {
+ ...BITableAnalysis,
+ parameters: {
+ ...BITableAnalysis.parameters,
+ // The dialog is portaled outside main, so a scene-only capture clips it.
+ testOptions: { ...BITableAnalysis.parameters?.testOptions, includeNavigationInSnapshot: true },
+ msw: {
+ mocks: {
+ ...BITableAnalysis.parameters?.msw.mocks,
+ post: {
+ ...BITableAnalysis.parameters?.msw.mocks.post,
+ '/api/environments/:team_id/query/HogQLQuery/': async ({ request }: MockResolverInfo) => {
+ const { query } = (await request.json()) as { query: { query: string } }
+ return query.query.startsWith('SELECT *')
+ ? {
+ columns: ['event', 'timestamp', 'revenue'],
+ types: [
+ ['event', 'String'],
+ ['timestamp', 'DateTime'],
+ ['revenue', 'Float64'],
+ ],
+ results: [
+ ['purchase', '2026-06-01 12:00:00', 20],
+ ['purchase', '2026-06-01 15:00:00', 100],
+ ],
+ hasMore: false,
+ }
+ : BITableAnalysis.parameters?.msw.mocks.post['/api/environments/:team_id/query/HogQLQuery/']
+ },
+ },
+ },
+ },
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement)
+ await userEvent.click(await canvas.findByRole('button', { name: /^Run$/ }))
+ await userEvent.click(await canvas.findByText('120', { exact: true }))
+ await userEvent.click(await within(document.body).findByRole('button', { name: 'View underlying rows' }))
+ await waitFor(() => expect(within(document.body).getByText('2026-06-01 12:00:00')).toBeVisible())
+ },
+}
+
+const BI_COMPARISON_CONFIG: BIConfig = {
+ ...BI_COMBO_CONFIG,
+ dateRange: { date_from: '-7d' },
+ compareFilter: { compare: true },
+ values: [BI_COMBO_CONFIG.values[0]],
+}
+
+export const BIOneClickComparison: Story = {
+ ...BICombinedMeasures,
+ parameters: {
+ ...BICombinedMeasures.parameters,
+ pageUrl: `${urls.businessIntelligence()}#${new URLSearchParams({ q: buildBIQuery(BI_COMPARISON_CONFIG)!.query, mode: 'bi', bi: JSON.stringify(BI_COMPARISON_CONFIG) })}`,
+ msw: {
+ mocks: {
+ ...BICombinedMeasures.parameters?.msw.mocks,
+ post: {
+ ...BICombinedMeasures.parameters?.msw.mocks.post,
+ '/api/environments/:team_id/query/HogQLQuery/': {
+ columns: ['bi_row_timestamp', 'sum_revenue', 'bi_comparison'],
+ types: [
+ ['bi_row_timestamp', 'DateTime'],
+ ['sum_revenue', 'Float64'],
+ ['bi_comparison', 'String'],
+ ],
+ results: [
+ ['2026-06-01', 120, 'Current period'],
+ ['2026-06-02', 210, 'Current period'],
+ ['2026-06-03', 180, 'Current period'],
+ ['2026-06-04', 245, 'Current period'],
+ ['2026-06-01', 100, 'Previous period'],
+ ['2026-06-02', 150, 'Previous period'],
+ ['2026-06-03', 120, 'Previous period'],
+ ['2026-06-04', 220, 'Previous period'],
+ ],
+ hasMore: false,
+ },
+ },
+ },
+ },
+ },
+}
+
+const BI_PIVOT_TOTALS_CONFIG: BIConfig = {
+ ...BI_ANALYSIS_CONFIG,
+ chartType: ChartDisplayType.TwoDimensionalHeatmap,
+ values: [BI_COMBO_CONFIG.values[0]],
+ totals: { rows: true, columns: true },
+}
+
+export const BIPivotTotals: Story = {
+ ...BITableAnalysis,
+ parameters: {
+ ...BITableAnalysis.parameters,
+ pageUrl: `${urls.businessIntelligence()}#${new URLSearchParams({ q: buildBIQuery(BI_PIVOT_TOTALS_CONFIG)!.query, mode: 'bi', bi: JSON.stringify(BI_PIVOT_TOTALS_CONFIG) })}`,
+ msw: {
+ mocks: {
+ ...BITableAnalysis.parameters?.msw.mocks,
+ post: {
+ ...BITableAnalysis.parameters?.msw.mocks.post,
+ '/api/environments/:team_id/query/HogQLQuery/': {
+ columns: ['bi_row_timestamp', 'bi_column_event', 'sum_revenue'],
+ types: [
+ ['bi_row_timestamp', 'String'],
+ ['bi_column_event', 'String'],
+ ['sum_revenue', 'Float64'],
+ ],
+ results: [
+ ['Total', 'Total', 340],
+ ['Total', 'purchase', 300],
+ ['Total', 'Other', 40],
+ ['2026-06-01', 'Total', 160],
+ ['2026-06-02', 'Total', 180],
+ ['2026-06-01', 'purchase', 120],
+ ['2026-06-02', 'purchase', 180],
+ ['2026-06-01', 'Other', 40],
+ ],
+ hasMore: false,
+ },
+ },
+ },
+ },
+ },
+}
diff --git a/products/business_intelligence/frontend/BIDrilldownModal.tsx b/products/business_intelligence/frontend/BIDrilldownModal.tsx
new file mode 100644
index 000000000000..6de007ea350b
--- /dev/null
+++ b/products/business_intelligence/frontend/BIDrilldownModal.tsx
@@ -0,0 +1,76 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonBanner, LemonButton, LemonModal } from '@posthog/lemon-ui'
+
+import { urls } from 'scenes/urls'
+
+import { Query } from '~/queries/Query/Query'
+
+import { BIDrilldownProps, biDrilldownLogic } from './biDrilldownLogic'
+
+export function BIDrilldownModal({ logicProps: props }: { logicProps: BIDrilldownProps }): JSX.Element {
+ const { selection, queries, showRows } = useValues(biDrilldownLogic(props))
+ const { close, viewRows } = useActions(biDrilldownLogic(props))
+ return (
+ <LemonModal title="Explore this result" isOpen={!!selection} onClose={close} width={showRows ? '90vw' : 520}>
+ {queries ? (
+ <div className="flex flex-col gap-3">
+ <p className="m-0">
+ {selection?.previous ? 'Comparison period' : 'Current period'} ·{' '}
+ {selection?.filters.length ? 'Selected dimensions' : 'All matching rows'}
+ </p>
+ {selection?.labels.length ? (
+ <ul className="m-0 pl-4">
+ {selection.labels.map((label, index) => (
+ <li key={index} className="break-words">
+ {label.name}: {label.value}
+ </li>
+ ))}
+ </ul>
+ ) : null}
+ <div className="flex flex-wrap gap-2">
+ <LemonButton
+ type="primary"
+ onClick={close}
+ to={
+ queries.worksheet
+ ? `${urls.businessIntelligence()}#q=${encodeURIComponent(JSON.stringify(queries.worksheet))}`
+ : undefined
+ }
+ disabledReason={
+ !queries.worksheet
+ ? 'Open comparison-period rows below to explore their original dates'
+ : undefined
+ }
+ >
+ Filter in new worksheet
+ </LemonButton>
+ <LemonButton
+ type="secondary"
+ onClick={viewRows}
+ disabledReason={showRows ? 'Underlying rows are already open' : undefined}
+ >
+ View underlying rows
+ </LemonButton>
+ <LemonButton type="secondary" to={urls.sqlEditor({ query: queries.rows })} onClick={close}>
+ Open in SQL editor
+ </LemonButton>
+ </div>
+ {showRows ? (
+ <>
+ <p className="m-0 text-secondary">
+ Showing up to 1,000 source rows, before aggregation or table calculations.
+ </p>
+ <Query query={queries.rows} uniqueKey={`${props.key}.underlying`} readOnly embedded />
+ </>
+ ) : null}
+ </div>
+ ) : (
+ <LemonBanner type="warning">
+ We couldn't build a query for this result. Close this window and check the worksheet's data source
+ and fields before trying again.
+ </LemonBanner>
+ )}
+ </LemonModal>
+ )
+}
diff --git a/products/business_intelligence/frontend/biAnalysis.ts b/products/business_intelligence/frontend/biAnalysis.ts
index a11216c84302..0a3c215adffd 100644
--- a/products/business_intelligence/frontend/biAnalysis.ts
+++ b/products/business_intelligence/frontend/biAnalysis.ts
@@ -2,6 +2,8 @@ import { BIConfig, BIField, BITableCalculation, BIValue } from '~/queries/schema
import { escapeHogQLString, escapeRawPropertyAsHogQLIdentifier } from '~/queries/utils'
import { ChartDisplayType } from '~/types'
+import { biComparisonCategory } from './biComparison'
+
export const BI_TABLE_CALCULATIONS: { value: BITableCalculation['type']; label: string }[] = [
{ value: 'percent_of_total', label: 'Percent of total' },
{ value: 'running_total', label: 'Running total' },
@@ -235,7 +237,7 @@ export function buildBIAnalysisQuery(config: BIConfig, input: BIAnalysisInput):
input.rows[0]
const breakdown = dimensions.find((dimension) => dimension !== xDimension)
select.push(
- `${breakdown ? `concat(bi_period, ' · ', toString(${displayed[dimensions.indexOf(breakdown)]}))` : 'bi_period'} AS bi_comparison`
+ `${breakdown ? `concat(bi_period, ' · ', ${biComparisonCategory(displayed[dimensions.indexOf(breakdown)])})` : 'bi_period'} AS bi_comparison`
)
}
let order = input.orderBy
diff --git a/products/business_intelligence/frontend/biComparison.ts b/products/business_intelligence/frontend/biComparison.ts
index b0ef8bca11da..0697f4f552ee 100644
--- a/products/business_intelligence/frontend/biComparison.ts
+++ b/products/business_intelligence/frontend/biComparison.ts
@@ -4,6 +4,13 @@ import { ChartDisplayType } from '~/types'
import { getBIDateField } from './biQueryFilters'
+export const BI_COMPARISON_EMPTY_LABEL = '(empty)'
+
+export function biComparisonCategory(expression: string): string {
+ const empty = escapeHogQLString(BI_COMPARISON_EMPTY_LABEL)
+ return `if(${expression} IS NULL, ${empty}, if(startsWith(toString(${expression}), ${empty}), concat(toString(${expression}), ' (category)'), toString(${expression})))`
+}
+
export function getBIComparisonDisabledReason(config: BIConfig): string | undefined {
if (!getBIDateField(config) || !config.dateRange?.date_from || config.dateRange.date_from === 'all') {
return 'Select a date column and a bounded date range first'
diff --git a/products/business_intelligence/frontend/biDrilldown.test.ts b/products/business_intelligence/frontend/biDrilldown.test.ts
new file mode 100644
index 000000000000..fe7a12491542
--- /dev/null
+++ b/products/business_intelligence/frontend/biDrilldown.test.ts
@@ -0,0 +1,159 @@
+import { BIConfig, BIField, BIVisualizationNode } from '~/queries/schema/schema-business-intelligence'
+import { NodeKind } from '~/queries/schema/schema-general'
+import { ChartDisplayType } from '~/types'
+
+import { getBIChartRecord, getBIDrillQueries, getBIDrillSelection, getBIEffectiveQuery } from './biDrilldown'
+import { buildBIQuery, DEFAULT_BI_CONFIG } from './biEditorTypes'
+
+const field = (name: string, type: BIField['type'] = 'string'): BIField => ({
+ id: name,
+ name,
+ expression: name,
+ type,
+ source: { table: 'events' },
+})
+const config: BIConfig = {
+ ...DEFAULT_BI_CONFIG,
+ source: { table: 'events' },
+ chartType: ChartDisplayType.ActionsBar,
+ rows: [{ ...field('timestamp', 'datetime'), dateBucket: 'day' }],
+ columns: [field('event')],
+ values: [{ field: field('properties.amount', 'float'), aggregation: 'sum' }],
+ dateRange: { date_from: '-7d' },
+ filters: [{ field: field('properties.environment'), operator: 'equals', value: 'production' }],
+}
+
+function buildWorksheet(config: BIConfig): { node: BIVisualizationNode } {
+ return { node: { ...buildBIQuery(config)!.node, kind: NodeKind.BIVisualizationNode, config } }
+}
+
+describe('BI drill-down', () => {
+ it('uses raw date and category values, escapes labels, and preserves effective dashboard filters', () => {
+ const node = buildWorksheet(config)!.node
+ node.source.variables = { variable: { variableId: 'variable', code_name: 'plan', value: 'starter' } }
+ const effective = getBIEffectiveQuery(
+ node,
+ { date_from: '-30d', filterTestAccounts: true },
+ { variable: { variableId: 'variable', code_name: 'plan', value: 'pro' } }
+ )
+ const record = getBIChartRecord(node, 'bi_row_timestamp', '2026-06-01', "purchase's")
+ const selection = getBIDrillSelection(config, record)
+ const queries = getBIDrillQueries(effective, selection)!
+ expect(queries.rows.source.query).toContain("toStartOfDay(timestamp) = '2026-06-01'")
+ expect(queries.rows.source.query).toContain("event = 'purchase\\'s'")
+ expect(queries.rows.source.query).toContain("properties.environment = 'production'")
+ expect(queries.rows.source.query).toContain('SELECT * FROM events')
+ expect(queries.rows.source.filters).toEqual({
+ dateRange: { date_from: '-30d', date_to: undefined, explicitDate: false },
+ filterTestAccounts: true,
+ })
+ expect(queries.rows.source.variables?.variable.value).toBe('pro')
+ expect(queries.worksheet?.source.variables?.variable.value).toBe('pro')
+ expect(node.source.variables?.variable.value).toBe('starter')
+ expect(queries.rows.source).not.toHaveProperty('biConfig')
+ expect(queries.worksheet?.config?.dateRange).toEqual({
+ date_from: '-30d',
+ date_to: undefined,
+ explicitDate: false,
+ })
+ expect(queries.worksheet?.config?.filters).toHaveLength(3)
+ expect(selection.filters.map(({ operator, value }) => ({ operator, value }))).toEqual([
+ { operator: 'equals', value: '2026-06-01' },
+ { operator: 'equals', value: "purchase's" },
+ ])
+ })
+
+ it.each([false, true])('converts numeric date dimensions to SQL dates (comparison: %s)', (previous) => {
+ const worksheet: BIConfig = {
+ ...config,
+ rows: [field('created_at', 'date')],
+ compareFilter: { compare: previous },
+ }
+ const selection = getBIDrillSelection(worksheet, {
+ bi_row_created_at: 1780272000,
+ bi_comparison: previous ? 'Previous period' : 'Current period',
+ })
+ const queries = getBIDrillQueries(buildWorksheet(worksheet).node, selection)!
+ expect(queries.rows.source.query).toContain(
+ previous ? "{filters.compareDate(created_at)} = '2026-06-01'" : "created_at = '2026-06-01'"
+ )
+ expect(queries.rows.source.query).not.toContain("'1780272000'")
+ })
+
+ it('uses comparison dates for previous-period points without treating their label as a category', () => {
+ const node = buildWorksheet({ ...config, compareFilter: { compare: true } })!.node
+ const record = getBIChartRecord(node, 'bi_row_timestamp', '2026-06-01', 'Previous period · purchase · web')
+ const selection = getBIDrillSelection(node.config, record)
+ const queries = getBIDrillQueries(node, selection)!
+ expect(selection.previous).toBe(true)
+ expect(queries.rows.source.query).toContain('{filters.previous}')
+ expect(queries.rows.source.query).toContain("toStartOfDay({filters.compareDate(timestamp)}) = '2026-06-01'")
+ expect(queries.rows.source.query).toContain("event = 'purchase · web'")
+ expect(queries.worksheet).toBeNull()
+ })
+
+ it('selects the remainder with null-safe membership and removes the top N restriction', () => {
+ const worksheet = { ...config, topN: { fieldId: 'event', count: 3, measureIndex: 0, includeOther: true } }
+ const selection = getBIDrillSelection(worksheet, { bi_column_event: 'Other' })
+ const queries = getBIDrillQueries(buildWorksheet(worksheet)!.node, selection)!
+ const sql = queries.rows.source.query
+ expect(sql).toContain('((event IS NOT NULL AND event IN')
+ expect(sql).toContain('= false')
+ expect(sql).toContain('WHERE bi_key IS NOT NULL')
+ expect(sql).toContain('GROUP BY bi_key ORDER BY sum(properties.amount) DESC, bi_key ASC LIMIT 3')
+ expect(sql).not.toContain("event = 'Other'")
+ expect(queries.worksheet?.config?.topN).toBeUndefined()
+ })
+
+ it.each([
+ ['Other (category)', "event = 'Other'"],
+ [null, 'event IS NULL'],
+ ])('distinguishes real Other and null from the remainder (%s)', (label, condition) => {
+ const worksheet = { ...config, topN: { fieldId: 'event', count: 3, measureIndex: 0, includeOther: true } }
+ const selection = getBIDrillSelection(worksheet, { bi_column_event: label })
+ const queries = getBIDrillQueries(buildWorksheet(worksheet)!.node, selection)!
+ expect(queries.rows.source.query).toContain(condition)
+ expect(queries.worksheet?.config?.topN).toBeUndefined()
+ })
+
+ it('expands pivot hierarchy keys and leaves subtotal dimensions unfiltered', () => {
+ const worksheet: BIConfig = {
+ ...config,
+ chartType: ChartDisplayType.TwoDimensionalHeatmap,
+ rows: [field('event'), field('properties.browser')],
+ columns: [field('properties.country')],
+ totals: { rows: true, columns: true, subtotals: true },
+ }
+ const selection = getBIDrillSelection(worksheet, {
+ bi_rows: '["purchase","Total"]',
+ bi_column_properties_country: 'US',
+ })
+ expect(selection.filters.map((filter) => [filter.field.name, filter.operator, filter.value])).toEqual([
+ ['event', 'equals', 'purchase'],
+ ['properties.country', 'equals', 'US'],
+ ])
+ expect(getBIDrillSelection(worksheet, { bi_rows: '["Total (category)","Total"]' }).filters[0]).toMatchObject({
+ operator: 'equals',
+ value: 'Total',
+ })
+ })
+
+ it('filters empty strings rather than silently dropping the selected category', () => {
+ const selection = getBIDrillSelection(config, { bi_column_event: '' })
+ expect(selection.filters[0]).toMatchObject({ operator: 'in', values: [''] })
+ expect(getBIDrillQueries(buildWorksheet(config)!.node, selection)!.rows.source.query).toContain("event IN ('')")
+ })
+
+ it.each([
+ ['(empty)', 'event IS NULL'],
+ ['(empty) (category)', "event = '(empty)'"],
+ ])('preserves the previous period for a null or literal empty label (%s)', (label, condition) => {
+ const worksheet = { ...config, compareFilter: { compare: true } }
+ const node = buildWorksheet(worksheet)!.node
+ expect(node.source.query).toContain("if(event IS NULL, '(empty)'")
+ const record = getBIChartRecord(node, 'bi_row_timestamp', '2026-06-01', `Previous period · ${label}`)
+ const selection = getBIDrillSelection(worksheet, record)
+ expect(selection.previous).toBe(true)
+ expect(getBIDrillQueries(node, selection)!.rows.source.query).toContain(condition)
+ })
+})
diff --git a/products/business_intelligence/frontend/biDrilldown.ts b/products/business_intelligence/frontend/biDrilldown.ts
new file mode 100644
index 000000000000..ab8441cd7ac1
--- /dev/null
+++ b/products/business_intelligence/frontend/biDrilldown.ts
@@ -0,0 +1,212 @@
+import { dayjs } from 'lib/dayjs'
+
+import { BIConfig, BIFilter, BIVisualizationNode } from '~/queries/schema/schema-business-intelligence'
+import {
+ DashboardFilter,
+ DataVisualizationNode,
+ HogQLVariable,
+ VisualizationNode,
+ NodeKind,
+} from '~/queries/schema/schema-general'
+import { escapeHogQLString } from '~/queries/utils'
+import { ChartDisplayType } from '~/types'
+
+import { BI_COMPARISON_EMPTY_LABEL, getBIComparisonDateExpression } from './biComparison'
+import {
+ buildBIQuery,
+ buildBIRowsQuery,
+ buildBITopMembership,
+ fieldExpression,
+ getBIResultDimensions,
+} from './biEditorTypes'
+
+export interface BIDrillSelection {
+ filters: BIFilter[]
+ previous: boolean
+ labels: { name: string; value: string }[]
+}
+
+export function getBIEffectiveQuery(
+ node: VisualizationNode,
+ override?: DashboardFilter | null,
+ variablesOverride?: Record<string, HogQLVariable> | null
+): VisualizationNode {
+ const filters = { ...node.source.filters }
+ if (override?.date_from || override?.date_to) {
+ filters.dateRange = {
+ date_from: override.date_from,
+ date_to: override.date_to,
+ explicitDate: !!override.explicitDate,
+ }
+ }
+ if (override?.properties?.length) {
+ filters.properties = [...(filters.properties ?? []), ...override.properties]
+ }
+ if (override?.filterTestAccounts != null) {
+ filters.filterTestAccounts = override.filterTestAccounts
+ }
+ if (override?.interval != null) {
+ filters.interval = override.interval
+ }
+ if (override?.breakdown_filter != null) {
+ filters.breakdownFilter = override.breakdown_filter
+ }
+ const variables = node.source.variables ? { ...node.source.variables } : undefined
+ for (const [id, variable] of Object.entries(variablesOverride ?? {})) {
+ if (variables?.[id]) {
+ variables[id] = { ...variables[id], value: variable.value, isNull: variable.isNull }
+ }
+ }
+ return { ...node, source: { ...node.source, filters, variables } }
+}
+
+export function getBIDrillSelection(config: BIConfig, record: Record<string, unknown>): BIDrillSelection {
+ const period = String(record.bi_comparison ?? '')
+ const previous = /^(Previous|Comparison) period(?: · |$)/.test(period)
+ const dimensions = getBIResultDimensions(config)
+ const filters: BIFilter[] = []
+ const labels: BIDrillSelection['labels'] = []
+ for (const { field, column, position } of dimensions) {
+ if (!(column in record)) {
+ continue
+ }
+ let value = record[column]
+ if (position !== undefined) {
+ try {
+ const values: unknown = typeof value === 'string' ? JSON.parse(value) : value
+ if (!Array.isArray(values) || position >= values.length) {
+ continue
+ }
+ value = values[position]
+ } catch {
+ continue
+ }
+ }
+ if (value === undefined) {
+ continue
+ }
+ const displayValue = value
+ if (config.totals?.rows || config.totals?.columns || config.totals?.subtotals) {
+ if (value === 'Total') {
+ continue
+ }
+ if (typeof value === 'string' && value.startsWith('Total') && value.endsWith(' (category)')) {
+ value = value.slice(0, -11)
+ }
+ }
+ const other = field.id === config.topN?.fieldId && config.topN?.includeOther
+ let filter: BIFilter
+ if (other && value === 'Other') {
+ const member = buildBITopMembership(config)
+ if (!member) {
+ continue
+ }
+ filter = { field, operator: 'custom', value: '', customExpression: `${member} = false`, enabled: true }
+ } else {
+ if (other && typeof value === 'string' && value.startsWith('Other') && value.endsWith(' (category)')) {
+ value = value.slice(0, -11)
+ }
+ const shiftedDate = previous && ['date', 'datetime'].includes(field.type)
+ const expression = fieldExpression(
+ shiftedDate ? { ...field, expression: getBIComparisonDateExpression(field) } : field
+ )
+ if (value instanceof Date) {
+ value = dayjs(value).format('YYYY-MM-DD HH:mm:ss')
+ }
+ if (typeof value === 'object' && value !== null) {
+ continue
+ }
+ if (typeof value === 'number' && !Number.isFinite(value)) {
+ continue
+ }
+ if (typeof value === 'number' && field.type === 'date') {
+ const date = dayjs.unix(value).utc()
+ if (!date.isValid()) {
+ continue
+ }
+ value = date.format('YYYY-MM-DD')
+ }
+ if (shiftedDate || typeof value === 'boolean') {
+ const literal = typeof value === 'boolean' ? String(value) : escapeHogQLString(String(value))
+ filter = {
+ field,
+ operator: 'custom',
+ value: '',
+ customExpression: value === null ? `${expression} IS NULL` : `${expression} = ${literal}`,
+ enabled: true,
+ }
+ } else {
+ filter =
+ value === null
+ ? { field, operator: 'is_not_set', value: '', enabled: true }
+ : String(value).trim()
+ ? { field, operator: 'equals', value: String(value), enabled: true }
+ : { field, operator: 'in', value: '', values: [String(value)], enabled: true }
+ }
+ }
+ filters.push(filter)
+ labels.push({ name: field.name, value: String(displayValue ?? '(empty)') })
+ }
+ return { filters, previous, labels }
+}
+
+export function getBIChartRecord(
+ node: VisualizationNode,
+ xColumn: string,
+ xValue: unknown,
+ breakdown?: string
+): Record<string, unknown> {
+ const record: Record<string, unknown> = { [xColumn]: xValue }
+ const config = node.kind === NodeKind.BIVisualizationNode ? node.config : undefined
+ if (breakdown !== undefined && config) {
+ const column = node.chartSettings?.seriesBreakdownColumn
+ if (column) {
+ record[column] = breakdown === '$$_posthog_breakdown_null_$$' ? null : breakdown
+ }
+ if (config.compareFilter?.compare) {
+ record.bi_comparison = breakdown
+ const dimension = getBIResultDimensions(config).find((dimension) => dimension.column !== xColumn)
+ if (dimension && /^(Current|Previous|Comparison) period · /.test(breakdown)) {
+ const category = breakdown.replace(/^(Current|Previous|Comparison) period · /, '')
+ record[dimension.column] =
+ category === BI_COMPARISON_EMPTY_LABEL
+ ? null
+ : category.startsWith(BI_COMPARISON_EMPTY_LABEL) && category.endsWith(' (category)')
+ ? category.slice(0, -11)
+ : category
+ }
+ }
+ }
+ return record
+}
+
+export function getBIDrillQueries(
+ node: VisualizationNode,
+ selection: BIDrillSelection
+): { rows: DataVisualizationNode; worksheet: BIVisualizationNode | null } | null {
+ const saved = node.kind === NodeKind.BIVisualizationNode ? node.config : undefined
+ if (!saved) {
+ return null
+ }
+ const config: BIConfig = {
+ ...saved,
+ dateRange: node.source.filters?.dateRange ?? saved.dateRange,
+ filters: [...saved.filters, ...selection.filters],
+ topN: undefined,
+ }
+ const source = buildBIRowsQuery(config, selection.previous)
+ if (!source) {
+ return null
+ }
+ source.filters = { ...source.filters, ...node.source.filters }
+ source.variables = node.source.variables
+ const generated = selection.previous ? null : buildBIQuery(config)?.node
+ const worksheet: BIVisualizationNode | null = generated
+ ? { ...generated, kind: NodeKind.BIVisualizationNode, config }
+ : null
+ if (worksheet) {
+ worksheet.source.filters = source.filters
+ worksheet.source.variables = source.variables
+ }
+ return { rows: { kind: NodeKind.DataVisualizationNode, source, display: ChartDisplayType.ActionsTable }, worksheet }
+}
diff --git a/products/business_intelligence/frontend/biDrilldownLogic.ts b/products/business_intelligence/frontend/biDrilldownLogic.ts
new file mode 100644
index 000000000000..353136cae095
--- /dev/null
+++ b/products/business_intelligence/frontend/biDrilldownLogic.ts
@@ -0,0 +1,90 @@
+import { MakeLogicType, actions, kea, key, path, props, reducers, selectors } from 'kea'
+
+import { VisualizationNode, NodeKind, DashboardFilter, HogQLVariable } from '~/queries/schema/schema-general'
+
+import { BIDrillSelection, getBIDrillQueries, getBIDrillSelection, getBIEffectiveQuery } from './biDrilldown'
+
+export interface BIDrilldownProps {
+ key: string
+ query: VisualizationNode
+ filtersOverride?: DashboardFilter | null
+ variablesOverride?: Record<string, HogQLVariable> | null
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface biDrilldownLogicValues {
+ queries: ReturnType<typeof getBIDrillQueries>
+ query: VisualizationNode
+ record: Record<string, unknown> | null
+ selection: BIDrillSelection | null
+ showRows: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface biDrilldownLogicActions {
+ close: () => {
+ value: true
+ }
+ inspect: (record: Record<string, unknown>) => {
+ record: Record<string, unknown>
+ }
+ viewRows: () => {
+ value: true
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface biDrilldownLogicMeta {
+ key: string
+ __keaTypeGenInternalSelectorTypes: {
+ query: (arg: any, arg2: any, arg3: any) => VisualizationNode
+ selection: (record: Record<string, unknown> | null, query: VisualizationNode) => BIDrillSelection | null
+ queries: (selection: BIDrillSelection | null, query: VisualizationNode) => ReturnType<typeof getBIDrillQueries>
+ }
+}
+
+export type biDrilldownLogicType = MakeLogicType<
+ biDrilldownLogicValues,
+ biDrilldownLogicActions,
+ BIDrilldownProps,
+ biDrilldownLogicMeta
+>
+
+export const biDrilldownLogic = kea<biDrilldownLogicType>([
+ props({} as BIDrilldownProps),
+ key((props) => props.key),
+ path((key) => ['products', 'business_intelligence', 'biDrilldownLogic', key]),
+ actions({ inspect: (record: Record<string, unknown>) => ({ record }), close: true, viewRows: true }),
+ reducers({
+ record: [
+ null as Record<string, unknown> | null,
+ {
+ inspect: (_, { record }) => record,
+ close: () => null,
+ },
+ ],
+ showRows: [false, { inspect: () => false, viewRows: () => true, close: () => false }],
+ }),
+ selectors({
+ query: [
+ () => [
+ (_, props) => props.query,
+ (_, props) => props.filtersOverride,
+ (_, props) => props.variablesOverride,
+ ],
+ (query, filters, variables): VisualizationNode => getBIEffectiveQuery(query, filters, variables),
+ ],
+ selection: [
+ (s) => [s.record, s.query],
+ (record: Record<string, unknown> | null, query: VisualizationNode): BIDrillSelection | null =>
+ record && query.kind === NodeKind.BIVisualizationNode
+ ? getBIDrillSelection(query.config, record)
+ : null,
+ ],
+ queries: [
+ (s) => [s.selection, s.query],
+ (selection: BIDrillSelection | null, query: VisualizationNode): ReturnType<typeof getBIDrillQueries> =>
+ selection ? getBIDrillQueries(query, selection) : null,
+ ],
+ }),
+])
diff --git a/products/business_intelligence/frontend/biEditorTypes.ts b/products/business_intelligence/frontend/biEditorTypes.ts
index 3e7d06ff7e48..f5dc799d4219 100644
--- a/products/business_intelligence/frontend/biEditorTypes.ts
+++ b/products/business_intelligence/frontend/biEditorTypes.ts
@@ -35,7 +35,7 @@ import {
isBIAnalysisConfig,
isBITableCalculation,
} from './biAnalysis'
-import { getBIComparisonDisabledReason, getBIComparisonDateExpression } from './biComparison'
+import { biComparisonCategory, getBIComparisonDisabledReason, getBIComparisonDateExpression } from './biComparison'
import { getBIMeasureSettings, isBIMeasureSettings, mergeBIMeasureSettings } from './biMeasureSettings'
import { getBIFiltersPlaceholder, getBIQueryFilters, normalizeBIDates } from './biQueryFilters'
@@ -640,7 +640,7 @@ function aggregationAlias(value: BIValue, index: number): string {
const DOTTED_IDENTIFIER_REGEX = /^[A-Za-z_$][A-Za-z0-9_$]*(?:\.[A-Za-z_$][A-Za-z0-9_$]*)*$/
-function fieldExpression(field: BIField): string {
+export function fieldExpression(field: BIField): string {
const expression = field.expression.trim() || field.name
const escapedExpression = DOTTED_IDENTIFIER_REGEX.test(expression)
? escapeDottedHogQLIdentifier(expression)
@@ -910,6 +910,67 @@ function computeBIQueryParts(config: BIConfig): BIQueryParts {
return { rowDimensions, columnDimensions, configuredValues }
}
+export function getBIResultDimensions(config: BIConfig): { field: BIField; column: string; position?: number }[] {
+ const { rowDimensions, columnDimensions } = computeBIQueryParts(config)
+ const dimensions = [...rowDimensions, ...columnDimensions]
+ if (config.chartType === ChartDisplayType.TwoDimensionalHeatmap) {
+ return [rowDimensions, columnDimensions].flatMap((side, index) =>
+ side.map(({ field, alias }, position) => ({
+ field,
+ column: side.length === 1 ? alias : index === 0 ? 'bi_rows' : 'bi_columns',
+ position: side.length > 1 ? position : undefined,
+ }))
+ )
+ }
+ const aliased =
+ hasBIAnalysis(config) ||
+ config.compareFilter?.compare ||
+ (dimensions.length === 2 &&
+ [
+ ChartDisplayType.Auto,
+ ChartDisplayType.ActionsBar,
+ ChartDisplayType.ActionsStackedBar,
+ ChartDisplayType.ActionsLineGraph,
+ ChartDisplayType.ActionsAreaGraph,
+ ].includes(config.chartType))
+ return dimensions.map(({ field, alias }) => ({ field, column: aliased ? alias : fieldExpression(field) }))
+}
+
+export function buildBIRowsQuery(config: BIConfig, previous = false): HogQLQuery | null {
+ if (!config.source || config.filters.some(getBIFilterValidationError)) {
+ return null
+ }
+ const placeholder = getBIFiltersPlaceholder(config)
+ const conditions = [
+ previous ? placeholder.replace('{filters', '{filters.previous') : placeholder,
+ ...config.filters.map(filterExpression).filter(Boolean),
+ ]
+ return {
+ kind: NodeKind.HogQLQuery,
+ connectionId: config.source.connectionId,
+ filters: getBIQueryFilters(config),
+ query: `SELECT * FROM ${escapePropertyAsHogQLIdentifier(config.source.table)} WHERE ${conditions.map((condition) => `(${condition})`).join(' AND ')} LIMIT 1000`,
+ }
+}
+
+export function buildBITopMembership(config: BIConfig): string | null {
+ const { rowDimensions, columnDimensions, configuredValues } = computeBIQueryParts(config)
+ const dimension = [...rowDimensions, ...columnDimensions].find(({ field }) => field.id === config.topN?.fieldId)
+ if (!dimension || !config.topN || !config.source) {
+ return null
+ }
+ const expression = fieldExpression(dimension.field)
+ const measure = config.values.length
+ ? configuredValues.find(({ value }) => value === config.values[config.topN!.measureIndex])?.expression
+ : 'count(*)'
+ if (!measure) {
+ return null
+ }
+ const conditions = [getBIFiltersPlaceholder(config), ...config.filters.map(filterExpression).filter(Boolean)]
+ const top = `SELECT ${expression} AS bi_key FROM ${escapePropertyAsHogQLIdentifier(config.source.table)} WHERE ${conditions.map((condition) => `(${condition})`).join(' AND ')} GROUP BY bi_key ORDER BY ${measure} DESC, bi_key ASC LIMIT ${config.topN.count}`
+ return `((${expression} IS NOT NULL AND ${expression} IN (SELECT bi_key FROM (${top}) WHERE bi_key IS NOT NULL)) OR (${expression} IS NULL AND (SELECT count(*) FROM (${top}) WHERE bi_key IS NULL) > 0))`
+}
+
const SORT_AGGREGATION_LABELS: Record<Exclude<BIAggregation, 'custom'>, string> = {
count: 'Count',
count_distinct: 'Count distinct',
@@ -1137,7 +1198,7 @@ export function buildBIQuery(config: BIConfig, probeForMoreRows = false): BIQuer
const periodLabel = config.compareFilter?.compare_to ? 'Comparison period' : 'Previous period'
const periodExpression = (label: string): string =>
breakdownDimension
- ? `concat(${escapeHogQLString(label + ' · ')}, toString(${fieldExpression(breakdownDimension.field)}))`
+ ? `concat(${escapeHogQLString(label + ' · ')}, ${biComparisonCategory(fieldExpression(breakdownDimension.field))})`
: escapeHogQLString(label)
const buildPeriod = (previous: boolean): string => {
const expressions = dimensions.map(({ field }) =>
diff --git a/products/business_intelligence/frontend/components/BIDateControls.tsx b/products/business_intelligence/frontend/components/BIDateControls.tsx
index 33a3f4c10197..fec26a1bfdcf 100644
--- a/products/business_intelligence/frontend/components/BIDateControls.tsx
+++ b/products/business_intelligence/frontend/components/BIDateControls.tsx
@@ -1,7 +1,7 @@
import { useActions, useValues } from 'kea'
import { IconCalendar } from '@posthog/icons'
-import { LemonSelect } from '@posthog/lemon-ui'
+import { LemonSelect, LemonSwitch } from '@posthog/lemon-ui'
import { CompareFilter } from 'lib/components/CompareFilter/CompareFilter'
import { DateFilter } from 'lib/components/DateFilter/DateFilter'
@@ -59,6 +59,13 @@ export function BIDateControls(): JSX.Element {
</>
)}
/>
+ <LemonSwitch
+ label="Compare previous period"
+ checked={!!config.compareFilter?.compare && !config.compareFilter.compare_to}
+ onChange={(compare) => setCompareFilter({ compare })}
+ disabledReason={getBIComparisonDisabledReason(config)}
+ size="small"
+ />
<CompareFilter
compareFilter={config.compareFilter}
updateCompareFilter={setCompareFilter}