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 table calculations totals and top n breakdowns (#112172)

Marius Andra87633d96638e
diff --git a/docs/published/handbook/engineering/data-warehouse.md b/docs/published/handbook/engineering/data-warehouse.md
index 16f30681430e..14f63e10ab47 100644
--- a/docs/published/handbook/engineering/data-warehouse.md
+++ b/docs/published/handbook/engineering/data-warehouse.md
@@ -52,6 +52,10 @@ 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 **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.
+
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 5315ea3499ab..1bb1a0cc81c9 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -1757,9 +1757,9 @@ snapshots:
components-mcp-use-case-card--surveys-create--light:
hash: v1.k794b7964.2ce59a009bfce14f01a88f688627cf4b1def20c28ce5124288a54f9c62ffd3a6.wIhKopBY00iVCPnC9GB4QncFt-dCm8Gq9Uz6FYXBZ68
components-message-tool-calls-editor--editable-tool-calls--dark:
- hash: v1.k794b7964.bf5d7e9a07a313eb905517ad07b3b9be0b7efe64532efc72fa97a824aa75a320.E85JvFQYNnizHUgjnQ9GPVwmu_6NIXmyHetF0eKWR70
+ hash: v1.k794b7964.7adaad1e91b71d0b933afe541a20fd43112e39d56d6638abadfae6a830bb0c15.TxnbKwXIG1XbB5e4KpRJa4-PA-wl-kKOWbtX1ERVqLU
components-message-tool-calls-editor--editable-tool-calls--light:
- hash: v1.k794b7964.e23addac27e56509f0caed349da836f0963b87500639d1097f948a5eff9942ec.DaRlPJVS3Kckngsx8aJC0uoIJYOHBm2xQh__x5rXYoY
+ hash: v1.k794b7964.4a10839159f5b3f989112539bb2a720f04460890fae5914a3516457e7cba92f3.Snir6e_iAMVVl1tdItfy70BRcAHw5Zem9Kk0ujjMQIo
components-navpanelproductpush--all-products--dark:
hash: v1.k794b7964.d6cc4da0e30950f4e3bf7338d86856529e48c45785bae5a85ccf4fd3ed7c3ad0.8n61Z9x6l3I3qfdAzk46yr7fAFHoYNdo3tjEKyJlcIo
components-navpanelproductpush--all-products--light:
@@ -9583,41 +9583,45 @@ 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.a367690805a7da1c693b589b73a8c2834446dc35e31b7b951bfc1bb308b3da7f.96-jw47y9XF2n27tdejWbZyKh7oCMNuXeG56vdP8IOI
+ hash: v1.k794b7964.112445f3b11134b83c65d57d144e29105836dc0e6fb04d2d8caf582ec3872a49.jiSutBC_C_bqfJ5ti5lBAIrl5B_XalZ2GWJmDe7o6w4
scenes-app-data-warehouse-sql-editor--bi-calculated-measure-editor--light:
- hash: v1.k794b7964.d5f258bb8353baae9fe035c1ef3328abc3b5e18a3a3039020049c1ec30ac1a2f.oljSnasVuvzFxotP42I-Y4gc4Gx_hMqzns0VnD6rrco
+ hash: v1.k794b7964.772040b3c483c6e5c74137a992300b5cebef552e1c089916e08ccd1f8a78d996.Px2nIepft0_wbdIwJ7K2sIgu_KMKDGd8Q5l4_2JKieY
scenes-app-data-warehouse-sql-editor--bi-connections--dark:
- hash: v1.k794b7964.d22365ff0e0f81154761b6e1546f0740202ebbfe0822c63c38cf1a7f96cc0190.hRB57dquUAeApUp4DWQG_umChjeK4py6CBHKcc1cXx0
+ hash: v1.k794b7964.68a247abe5613ad8541e9a5c47678fd074f6619e46a832b8cf696cbe0f21c246.4pP8_mvPsbkJ1IaEa4gquPqEUfoqmuvai3Whh9MM4MQ
scenes-app-data-warehouse-sql-editor--bi-connections--light:
- hash: v1.k794b7964.048a336018dfc49f0c315364f24e154d45897d50ee8698a3dc51b026503ce065.sjsvVZmHY4g5D9MUjD1W4xI2zqgwDFyAYzTAihKzx3E
+ hash: v1.k794b7964.3c378345f3e726de2c55d29f40731d21c18c7e8bdbc8ab0b3066289c16c1ff51.AMQFda_DBOe1OmH9zh15CyRiZk1pXZ3DZsFel3i7wb8
scenes-app-data-warehouse-sql-editor--bi-data-source-picker--dark:
- hash: v1.k794b7964.93abc39bb6481de815221c0fc8e20b3388c66f90dc4bf07f9b55e5577405d671.eHsrBCsMk3JHFeHTdyRPVSnx8wGOJGaLFWD-Te-eyjQ
+ hash: v1.k794b7964.0e1874e222a28a0d6a539ebcfb01e4fb7e865659ee9aefc89713c03c6b0df6e5.nW-1R-RnJ16aJQKeTb9-qBDdbcjur1nzOkEVUeF4d-s
scenes-app-data-warehouse-sql-editor--bi-data-source-picker--light:
- hash: v1.k794b7964.e23f5b15f3c99bf3064768fd3a048a436e9b443117cfc0a00c4d73a3f4ba2f22.nxKhSmvyyrnC7kdphG8cL24MkT9I2nGDK4vfruY2Vw0
+ hash: v1.k794b7964.a16b0358b85d99553e7eba6163e3465651f1604d6758570c7c6f13670249ef0f.HyuK9AsBBZnmPCE0UBIYDkp3JeWyyBiUOdyMZPPifY8
scenes-app-data-warehouse-sql-editor--bi-edit-saved-insight--dark:
- hash: v1.k794b7964.be1c7af3ea56ab263804c40dc88ee390b48279b51f0843223572c4a6d6e3dd6e.NAhufubM0yajuhGMw8mZOiSJwNwAX5nSIXUDvx7SVhc
+ hash: v1.k794b7964.2ca8f806fa53e888b3dcd4c7e032ac3b64d155d7d44c21a46e54c837a797cf02.VpG0HDzGUJzhM6A6jBaehRWU7HAbonfThg1j53F6gGo
scenes-app-data-warehouse-sql-editor--bi-edit-saved-insight--light:
- hash: v1.k794b7964.dbe9d7e7f469dfb7eb4ec9109b10d1fba19239b46bfee80ea915daf4532c935b.ZLFZ6KVb6v80JYsVv68pSmtqkFJE0pBnxW4FvOnvm08
+ hash: v1.k794b7964.5408f40d308350da0578a1cf03e761f1a4f44aaf816ce58ec1c5bc2c73b12b92.7d4bvJcvZmpsO-mH3ELmGv6Kljg8L-O8qUnmI3DrZxw
scenes-app-data-warehouse-sql-editor--bi-empty-worksheet--dark:
- hash: v1.k794b7964.a396976c1ac19d1018d181cb7a1a45b9094c1afae27b09ce5c47370dbd32719e.8W7iOXmHeV_jCUjH5EIjAg3Le0HCj-m8Uf0zVxal0ic
+ hash: v1.k794b7964.3b20f018c13b2df3cea913d996e05b2233d28ae85f4293233dc74f2f112e2710.-UEiBxfiTSb_fN2SiUTLj1jAEEXR0eAbpda4Dp2Zluk
scenes-app-data-warehouse-sql-editor--bi-empty-worksheet--light:
- hash: v1.k794b7964.5b94e2bde6e76fca16d810c564720fbaee3d25678eff894cb660766da8f86a0b.sPgfzc_N0i2i0a80EUTnLmvKajKY4Y5V8QKI_6R0PdE
+ hash: v1.k794b7964.4339d48fbc96a0cd5d68006f2e9357722eeaf745a97ff2b1617dd14f5c05c4c7.tTXtWEaRb4Bbi1vJC2zMYbckBPgnMjSJMdV64h8B-ys
scenes-app-data-warehouse-sql-editor--bi-mode-worksheet--dark:
- hash: v1.k794b7964.e84877e73e6815011e2aca7c2d89844ec1fe5189781f52e440eed3c7ac78a7d5.PJfFdwO_LSix6NQonl97nVuqgHKVQORBqF3mcu8VYqg
+ hash: v1.k794b7964.9c9e07c2bf804e0087b31e1e6e09bf3340d922bea1fa1a2b89125242938d303f.TM7wxn9EX5uxZBjKUiMyai6vXfA8Penn8CKBRXthJ8c
scenes-app-data-warehouse-sql-editor--bi-mode-worksheet--light:
- hash: v1.k794b7964.bc5edcd1a6f2724d2f77bdd940b7e932a86fd463453a4faaa0a796971856244f.j7E6Gaa4jFPmH5g5mRJaKpUfiFVrjgrHhKY_xzEKzhg
+ hash: v1.k794b7964.0544630a02d08ece24e4d22a788de3e0764e620b06baec57db15603cb34664f5.1HoUN3bJewk6AkCT66bG1dNjdqzk7FdQjy2NQoQs-3g
scenes-app-data-warehouse-sql-editor--bi-quick-filters--dark:
- hash: v1.k794b7964.51aa1c7d5872eb708a864b09fe99c90ce0656d672ae463c4977b79f239787268.uvA-AuIOaJ8dqlKJSewyHTH7rw8Qu78Zc_P1-Esi5ok
+ hash: v1.k794b7964.9f2b96b909d18de8ef55b8874c435f3c3af3365cd062f05881b22f471facd758.St3DcMSxFLWWL6AJVAzonXz6UiD7ue63VECETosFKsQ
scenes-app-data-warehouse-sql-editor--bi-quick-filters--light:
- hash: v1.k794b7964.bc2b0e11f3a6f0b6945f8a650dc2d38e835718a6286ee76eab8ed4c5b53be026.zyksMUf8n3P02oTMl_V7_qsXoLmUE2tjS_hGbuNwlPI
+ hash: v1.k794b7964.a2351c2ef95978673a75ccbdd79309333b385e0438a953f90a2aef25e1403eee.gMOzglcHr-juG-7Jw2yQj3Okwe5Z626RSynL968fvW4
scenes-app-data-warehouse-sql-editor--bi-quick-filters-narrow--dark:
- hash: v1.k794b7964.fae0f140959005592540515048113be87e37da44cc2f2bc43c235d42c029fc09.y-lrow6x4OgImDWCeHhxGFAqF9629_pTfS-sl3MadtY
+ hash: v1.k794b7964.f9621aa7fac64ee76f1b5bef72cb44b4ed52a18970b3f73da97b0679793646f1.6Tm5b5oHeUO9Zws9KgTToRjKcQXVDob-6nhXQD20vDI
scenes-app-data-warehouse-sql-editor--bi-quick-filters-narrow--light:
- hash: v1.k794b7964.70e1e001dd7bd0e941c854bd3202c55934bd5298dd94362ce221b2582b545a29.F5XoYtMr2_wNfTZGx7Y2rD7YTCjsSE2xZhisJ8KS1EE
+ hash: v1.k794b7964.6506e7fcc81caabe234e2644ebc1f4c80b13787f352d9dcb49e8bedf8b18c252.SjdnqsFqsy2a0Xr1eVN5Y3VFTbnHbZZJDe7a3bKmgPQ
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.b88db4600104e34c32ef84219e01c122cece90127b1f3ac027201c3be78a1487.pebp_UGlsVHrk24xHZ10anHIDf3X9iDjxsqOYozG3OM
+ scenes-app-data-warehouse-sql-editor--bi-table-analysis--light:
+ hash: v1.k794b7964.bcd2f6f05961c1471d2dc93fb5f44c794c6b0a3aca5d3929fe669ebae21c1dab.Vz9NrHtaiU7g9Gy_vMIZwJOC6T5ptaab7emZB3im3nU
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/nodes/DataVisualization/Components/seriesBreakdownLogic.ts b/frontend/src/queries/nodes/DataVisualization/Components/seriesBreakdownLogic.ts
index 333453cd7566..8aabe00fd301 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/seriesBreakdownLogic.ts
+++ b/frontend/src/queries/nodes/DataVisualization/Components/seriesBreakdownLogic.ts
@@ -3,23 +3,7 @@ import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path,
import { DataColorTheme } from 'lib/colors'
import { dataThemeLogic, getColorFromToken } from 'scenes/dataThemeLogic'
-import type {
- ChartSettings,
- VisualizationNode,
- ErrorTrackingQueryResponse,
- HogQLAutocompleteResponse,
- HogQLMetadataResponse,
- HogQLQueryResponse,
- HogQueryResponse,
- LogAttributesQueryResponse,
- LogValuesQueryResponse,
- MetricsQueryResponse,
- SessionsQueryResponse,
- TraceSpansAggregationQueryResponse,
- TraceSpansAttributeBreakdownQueryResponse,
- TraceSpansQueryResponse,
-} from '../../../schema/schema-general'
-import type { TraceSpansTreeQueryResponse } from '../../../schema/schema-general'
+import type { AnyResponseType, ChartSettings, VisualizationNode } from '../../../schema/schema-general'
import { AxisSeries, AxisSeriesSettings, SelectedYAxis, dataVisualizationLogic } from '../dataVisualizationLogic'
import type { Column } from '../dataVisualizationLogic'
import { humanizeEventColumnValue } from '../eventColumnLabels'
@@ -101,22 +85,7 @@ export interface seriesBreakdownLogicValues {
chartSettings: ChartSettings // dataVisualizationLogic
columns: Column[] // dataVisualizationLogic
query: VisualizationNode // dataVisualizationLogic
- response:
- | ErrorTrackingQueryResponse
- | HogQLAutocompleteResponse
- | HogQLMetadataResponse
- | HogQLQueryResponse<any[]>
- | HogQueryResponse
- | LogAttributesQueryResponse
- | LogValuesQueryResponse
- | MetricsQueryResponse
- | Record<string, any>
- | SessionsQueryResponse
- | TraceSpansAggregationQueryResponse
- | TraceSpansAttributeBreakdownQueryResponse
- | TraceSpansQueryResponse
- | TraceSpansTreeQueryResponse
- | null // dataVisualizationLogic
+ response: AnyResponseType | null // dataVisualizationLogic
selectedXAxis: string | null // dataVisualizationLogic
selectedYAxis: (SelectedYAxis | null)[] | null // dataVisualizationLogic
breakdownColumnValues: string[]
@@ -135,22 +104,7 @@ export interface seriesBreakdownLogicActions {
} // dataVisualizationLogic
addSeriesBreakdown: (columnName: string | null) => {
columnName: string | null
- response:
- | ErrorTrackingQueryResponse
- | HogQLAutocompleteResponse
- | HogQLMetadataResponse
- | HogQLQueryResponse<any[]>
- | HogQueryResponse
- | LogAttributesQueryResponse
- | LogValuesQueryResponse
- | MetricsQueryResponse
- | Record<string, any>
- | SessionsQueryResponse
- | TraceSpansAggregationQueryResponse
- | TraceSpansAttributeBreakdownQueryResponse
- | TraceSpansQueryResponse
- | TraceSpansTreeQueryResponse
- | null
+ response: AnyResponseType | null
}
deleteSeriesBreakdown: () => {}
}
@@ -163,22 +117,7 @@ export interface seriesBreakdownLogicMeta {
showSeriesBreakdown: (selectedSeriesBreakdownColumn: string | null | undefined) => boolean
breakdownColumnValues: (
selectedSeriesBreakdownColumn: string | null | undefined,
- response:
- | ErrorTrackingQueryResponse
- | HogQLAutocompleteResponse
- | HogQLMetadataResponse
- | HogQLQueryResponse<any[]>
- | HogQueryResponse
- | LogAttributesQueryResponse
- | LogValuesQueryResponse
- | MetricsQueryResponse
- | Record<string, any>
- | SessionsQueryResponse
- | TraceSpansAggregationQueryResponse
- | TraceSpansAttributeBreakdownQueryResponse
- | TraceSpansQueryResponse
- | TraceSpansTreeQueryResponse
- | null,
+ response: AnyResponseType | null,
columns: Column[]
) => string[]
seriesBreakdownData: (
@@ -186,22 +125,7 @@ export interface seriesBreakdownLogicMeta {
breakdownColumnValues: string[],
selectedYAxis: (SelectedYAxis | null)[] | null,
selectedXAxis: string | null,
- response:
- | ErrorTrackingQueryResponse
- | HogQLAutocompleteResponse
- | HogQLMetadataResponse
- | HogQLQueryResponse<any[]>
- | HogQueryResponse
- | LogAttributesQueryResponse
- | LogValuesQueryResponse
- | MetricsQueryResponse
- | Record<string, any>
- | SessionsQueryResponse
- | TraceSpansAggregationQueryResponse
- | TraceSpansAttributeBreakdownQueryResponse
- | TraceSpansQueryResponse
- | TraceSpansTreeQueryResponse
- | null,
+ response: AnyResponseType | null,
columns: Column[],
chartSettings: ChartSettings,
getTheme: (themeId: number | string | null | undefined) => DataColorTheme | null
diff --git a/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx b/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx
index b85c65c47278..35a06b0fd3b9 100644
--- a/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx
+++ b/frontend/src/queries/nodes/DataVisualization/DataVisualization.tsx
@@ -4,7 +4,7 @@ import { router } from 'kea-router'
import { useCallback, useRef, useState } from 'react'
import { IconGear } from '@posthog/icons'
-import { LemonButton, LemonDivider } from '@posthog/lemon-ui'
+import { LemonBanner, LemonButton, LemonDivider } from '@posthog/lemon-ui'
import { ExportButton } from 'lib/components/ExportButton/ExportButton'
import { PIE_DISPLAY_TYPES } from 'lib/constants'
@@ -28,6 +28,7 @@ import { shouldQueryBeAsync } from '~/queries/utils'
import { ChartDisplayType, ExportContext, ExporterFormat, InsightLogicProps } from '~/types'
import { alertsToThresholdGoalLines, insightAlertsLogic } from 'products/alerts/frontend/logic/insightAlertsLogic'
+import { getBIVisualizationSource } from 'products/business_intelligence/frontend/biQueryResults'
import { HogQLBoldNumber } from 'products/product_analytics/frontend/insights/shared/BoldNumber/BoldNumber'
import { DataNodeLogicProps, dataNodeLogic } from '../DataNode/dataNodeLogic'
@@ -116,7 +117,7 @@ export function DataTableVisualization({
}
const dataNodeLogicProps: DataNodeLogicProps = {
- query: query.source,
+ query: getBIVisualizationSource(query),
key: vizKey,
cachedResults,
loadPriority: insightProps.loadPriority,
@@ -137,7 +138,8 @@ export function DataTableVisualization({
sourceQuery: query,
setQuery: setQuery,
onUpdate: (query: VisualizationNode) => {
- loadData(shouldQueryBeAsync(query.source) ? 'force_async' : 'force_blocking', undefined, query.source)
+ const source = getBIVisualizationSource(query)
+ loadData(shouldQueryBeAsync(source) ? 'force_async' : 'force_blocking', undefined, source)
},
}
@@ -357,6 +359,16 @@ 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.test.ts b/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.test.ts
index df4d8d3736de..881a62ec8dee 100644
--- a/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.test.ts
+++ b/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.test.ts
@@ -1,9 +1,13 @@
import { expectLogic } from 'kea-test-utils'
+import { queryExportContext } from '~/queries/query'
import { ConditionalFormattingRule, VisualizationNode, NodeKind } from '~/queries/schema/schema-general'
import { initKeaTests } from '~/test/init'
import { ChartDisplayType } from '~/types'
+import { buildBIQuery, DEFAULT_BI_CONFIG } from 'products/business_intelligence/frontend/biEditorTypes'
+import { getBIVisualizationSource } from 'products/business_intelligence/frontend/biQueryResults'
+
import { dataNodeLogic } from '../DataNode/dataNodeLogic'
import {
AxisSeriesSettings,
@@ -52,6 +56,41 @@ describe('dataVisualizationLogic', () => {
logic.unmount()
})
+ test.each([
+ [true, 0, false],
+ [true, 99, false],
+ [true, 100, false],
+ [true, 101, true],
+ [false, 101, false],
+ ])('caps BI=%s results with %i rows before building chart series', (bi, rowCount, hasMore) => {
+ logic.unmount()
+ const config = { ...DEFAULT_BI_CONFIG, source: { table: 'events' }, limit: 100 as const }
+ const source = buildBIQuery(config)!.node.source
+ const query: VisualizationNode = bi
+ ? { kind: NodeKind.BIVisualizationNode, config, source, display: ChartDisplayType.ActionsBar }
+ : { ...defaultQuery, source, display: ChartDisplayType.ActionsBar }
+ const response = {
+ columns: ['label', 'value'],
+ types: [
+ ['label', 'String'],
+ ['value', 'Int64'],
+ ],
+ results: Array.from({ length: rowCount }, (_, index) => [`row-${index}`, index]),
+ }
+ logic = dataVisualizationLogic({ key: testKey, query, dataNodeCollectionId, cachedResults: response })
+ logic.mount()
+
+ const expectedRows = bi ? Math.min(rowCount, 100) : rowCount
+ expect(logic.values.response).toMatchObject({ results: response.results.slice(0, expectedRows) })
+ expect(logic.values.xData?.data).toHaveLength(expectedRows)
+ expect(logic.values.yData?.[0].data).toHaveLength(expectedRows)
+ expect(logic.values.hasMoreData).toBe(hasMore)
+ expect(getBIVisualizationSource(query).query).toMatch(new RegExp(`LIMIT ${bi ? 101 : 100}$`))
+ expect(query.source.query).toMatch(/LIMIT 100$/)
+ expect(queryExportContext(query)).toMatchObject({ source: { query: source.query } })
+ expect(response.results).toHaveLength(rowCount)
+ })
+
test.each([
{
name: 'shows a big number for a single numeric column',
diff --git a/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.ts b/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.ts
index 98ceb6dcdd01..8f476202c132 100644
--- a/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.ts
+++ b/frontend/src/queries/nodes/DataVisualization/dataVisualizationLogic.ts
@@ -46,6 +46,11 @@ import {
import { QueryContext } from '~/queries/types'
import { ChartDisplayType, DashboardType } from '~/types'
+import {
+ getBIVisualizationResponse,
+ getBIVisualizationSource,
+} from 'products/business_intelligence/frontend/biQueryResults'
+
import type {
DataNode,
ErrorTrackingQueryResponse,
@@ -636,9 +641,9 @@ interface HogVm {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface dataVisualizationLogicValues {
- hasMoreData: boolean // dataNodeLogic
queryCancelled: boolean // dataNodeLogic
- response:
+ rawHasMoreData: boolean // dataNodeLogic
+ rawResponse:
| ErrorTrackingQueryResponse
| HogQLAutocompleteResponse
| HogQLMetadataResponse
@@ -669,6 +674,7 @@ export interface dataVisualizationLogicValues {
dataVisualizationProps: DataVisualizationLogicProps
effectiveVisualizationType: ChartDisplayType
hasDateTimeColumns: boolean
+ hasMoreData: boolean
hasSortedTable: boolean
hogVm: HogVm | null
hogVmLoadError: unknown
@@ -684,6 +690,7 @@ export interface dataVisualizationLogicValues {
pinnedColumns: string[]
presetChartHeight: boolean
query: VisualizationNode
+ response: AnyResponseType | null
selectedXAxis: string | null
selectedYAxis: (SelectedYAxis | null)[] | null
showEditingUI: boolean
@@ -844,8 +851,9 @@ export interface dataVisualizationLogicMeta {
) => void | Promise<void>
}
__keaTypeGenInternalSelectorTypes: {
- columns: (
- response:
+ response: (
+ query: VisualizationNode,
+ rawResponse:
| ErrorTrackingQueryResponse
| HogQLAutocompleteResponse
| HogQLMetadataResponse
@@ -861,7 +869,9 @@ export interface dataVisualizationLogicMeta {
| TraceSpansQueryResponse
| TraceSpansTreeQueryResponse
| null
- ) => Column[]
+ ) => AnyResponseType | null
+ hasMoreData: (response: AnyResponseType | null, rawHasMoreData: boolean) => boolean
+ columns: (response: AnyResponseType | null) => Column[]
numericalColumns: (columns: Column[]) => Column[]
hasDateTimeColumns: (columns: Column[]) => boolean
dashboardId: (arg: any) => any
@@ -873,84 +883,24 @@ export interface dataVisualizationLogicMeta {
isTransposed: (query: VisualizationNode) => boolean
yData: (
selectedYAxis: (SelectedYAxis | null)[] | null,
- response:
- | ErrorTrackingQueryResponse
- | HogQLAutocompleteResponse
- | HogQLMetadataResponse
- | HogQLQueryResponse<any[]>
- | HogQueryResponse
- | LogAttributesQueryResponse
- | LogValuesQueryResponse
- | MetricsQueryResponse
- | Record<string, any>
- | SessionsQueryResponse
- | TraceSpansAggregationQueryResponse
- | TraceSpansAttributeBreakdownQueryResponse
- | TraceSpansQueryResponse
- | TraceSpansTreeQueryResponse
- | null,
+ response: AnyResponseType | null,
columns: Column[],
chartSettings: ChartSettings,
effectiveVisualizationType: ChartDisplayType
) => AxisSeries<number | null>[]
xData: (
selectedXAxis: string | null,
- response:
- | ErrorTrackingQueryResponse
- | HogQLAutocompleteResponse
- | HogQLMetadataResponse
- | HogQLQueryResponse<any[]>
- | HogQueryResponse
- | LogAttributesQueryResponse
- | LogValuesQueryResponse
- | MetricsQueryResponse
- | Record<string, any>
- | SessionsQueryResponse
- | TraceSpansAggregationQueryResponse
- | TraceSpansAttributeBreakdownQueryResponse
- | TraceSpansQueryResponse
- | TraceSpansTreeQueryResponse
- | null,
+ response: AnyResponseType | null,
columns: Column[]
) => AxisSeries<string> | null
sourceTabularColumns: (
tabularColumnSettings: (SelectedYAxis | null)[] | null,
- response:
- | ErrorTrackingQueryResponse
- | HogQLAutocompleteResponse
- | HogQLMetadataResponse
- | HogQLQueryResponse<any[]>
- | HogQueryResponse
- | LogAttributesQueryResponse
- | LogValuesQueryResponse
- | MetricsQueryResponse
- | Record<string, any>
- | SessionsQueryResponse
- | TraceSpansAggregationQueryResponse
- | TraceSpansAttributeBreakdownQueryResponse
- | TraceSpansQueryResponse
- | TraceSpansTreeQueryResponse
- | null,
+ response: AnyResponseType | null,
columns: Column[]
) => AxisSeries<any>[]
sourceTabularData: (
sourceTabularColumns: AxisSeries<any>[],
- response:
- | ErrorTrackingQueryResponse
- | HogQLAutocompleteResponse
- | HogQLMetadataResponse
- | HogQLQueryResponse<any[]>
- | HogQueryResponse
- | LogAttributesQueryResponse
- | LogValuesQueryResponse
- | MetricsQueryResponse
- | Record<string, any>
- | SessionsQueryResponse
- | TraceSpansAggregationQueryResponse
- | TraceSpansAttributeBreakdownQueryResponse
- | TraceSpansQueryResponse
- | TraceSpansTreeQueryResponse
- | null,
+ response: AnyResponseType | null,
chartSettings: ChartSettings
) => TableDataCell<any>[][]
tabularColumns: (
@@ -968,25 +918,7 @@ export interface dataVisualizationLogicMeta {
visualizationType: ChartDisplayType,
autoVisualizationType: ChartDisplayType
) => ChartDisplayType
- autoVisualizationType: (
- columns: Column[],
- response:
- | ErrorTrackingQueryResponse
- | HogQLAutocompleteResponse
- | HogQLMetadataResponse
- | HogQLQueryResponse<any[]>
- | HogQueryResponse
- | LogAttributesQueryResponse
- | LogValuesQueryResponse
- | MetricsQueryResponse
- | Record<string, any>
- | SessionsQueryResponse
- | TraceSpansAggregationQueryResponse
- | TraceSpansAttributeBreakdownQueryResponse
- | TraceSpansQueryResponse
- | TraceSpansTreeQueryResponse
- | null
- ) => ChartDisplayType
+ autoVisualizationType: (columns: Column[], response: AnyResponseType | null) => ChartDisplayType
needsHogVm: (
visualizationType: ChartDisplayType,
effectiveVisualizationType: ChartDisplayType,
@@ -1018,13 +950,19 @@ export const dataVisualizationLogic = kea<dataVisualizationLogicType>([
dataNodeLogic({
cachedResults: props.cachedResults,
key: props.key,
- query: props.query.source,
+ query: getBIVisualizationSource(props.query),
dataNodeCollectionId: props.dataNodeCollectionId,
loadPriority: props.loadPriority,
variablesOverride: props.variablesOverride,
limitContext: props.limitContext,
}),
- ['response', 'responseLoading', 'responseError', 'queryCancelled', 'hasMoreData'],
+ [
+ 'response as rawResponse',
+ 'responseLoading',
+ 'responseError',
+ 'queryCancelled',
+ 'hasMoreData as rawHasMoreData',
+ ],
themeLogic,
['isDarkModeOn'],
sceneLogic,
@@ -1034,7 +972,7 @@ export const dataVisualizationLogic = kea<dataVisualizationLogicType>([
dataNodeLogic({
cachedResults: props.cachedResults,
key: props.key,
- query: props.query.source,
+ query: getBIVisualizationSource(props.query),
dataNodeCollectionId: props.dataNodeCollectionId,
loadPriority: props.loadPriority,
variablesOverride: props.variablesOverride,
@@ -1429,6 +1367,16 @@ export const dataVisualizationLogic = kea<dataVisualizationLogicType>([
],
})),
selectors({
+ response: [
+ (s) => [s.query, s.rawResponse],
+ (query: VisualizationNode, response: AnyResponseType | null): AnyResponseType | null =>
+ getBIVisualizationResponse(query, response),
+ ],
+ hasMoreData: [
+ (s) => [s.response, s.rawHasMoreData],
+ (response: AnyResponseType | null, rawHasMoreData: boolean): boolean =>
+ !!(response && 'hasMore' in response && response.hasMore) || rawHasMoreData,
+ ],
columns: [
(s) => [s.response],
(
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index e4c3040c1892..f3c2c1e56043 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -6209,6 +6209,12 @@
}
]
},
+ "topN": {
+ "$ref": "#/definitions/BITopN"
+ },
+ "totals": {
+ "$ref": "#/definitions/BITotals"
+ },
"values": {
"items": {
"$ref": "#/definitions/BIValue"
@@ -6330,6 +6336,62 @@
"enum": ["asc", "desc"],
"type": "string"
},
+ "BITableCalculation": {
+ "additionalProperties": false,
+ "properties": {
+ "computeUsing": {
+ "description": "Dimension ID to traverse. Unset chooses the date dimension; 'table' traverses all dimensions.",
+ "type": "string"
+ },
+ "type": {
+ "$ref": "#/definitions/BITableCalculationType"
+ },
+ "window": {
+ "$ref": "#/definitions/positive_integer",
+ "description": "Number of points, including the current point, in a trailing moving average."
+ }
+ },
+ "required": ["type"],
+ "type": "object"
+ },
+ "BITableCalculationType": {
+ "enum": ["percent_of_total", "running_total", "difference", "percent_change", "moving_average", "rank"],
+ "type": "string"
+ },
+ "BITopN": {
+ "additionalProperties": false,
+ "properties": {
+ "count": {
+ "$ref": "#/definitions/positive_integer"
+ },
+ "fieldId": {
+ "type": "string"
+ },
+ "includeOther": {
+ "type": "boolean"
+ },
+ "measureIndex": {
+ "$ref": "#/definitions/non_negative_integer"
+ }
+ },
+ "required": ["fieldId", "count", "measureIndex", "includeOther"],
+ "type": "object"
+ },
+ "BITotals": {
+ "additionalProperties": false,
+ "properties": {
+ "columns": {
+ "type": "boolean"
+ },
+ "rows": {
+ "type": "boolean"
+ },
+ "subtotals": {
+ "type": "boolean"
+ }
+ },
+ "type": "object"
+ },
"BIValue": {
"additionalProperties": false,
"properties": {
@@ -6344,6 +6406,9 @@
},
"label": {
"type": "string"
+ },
+ "tableCalculation": {
+ "$ref": "#/definitions/BITableCalculation"
}
},
"required": ["field", "aggregation"],
diff --git a/frontend/src/queries/schema/schema-business-intelligence.ts b/frontend/src/queries/schema/schema-business-intelligence.ts
index 1e6b09170f7a..67af8f47ac61 100644
--- a/frontend/src/queries/schema/schema-business-intelligence.ts
+++ b/frontend/src/queries/schema/schema-business-intelligence.ts
@@ -10,6 +10,7 @@ import {
NodeKind,
TableSettings,
} from './schema-general'
+import { non_negative_integer, positive_integer } from './type-utils'
export interface BIVisualizationNode extends Node<never> {
kind: NodeKind.BIVisualizationNode
@@ -66,6 +67,36 @@ export interface BIValue {
aggregation: BIAggregation
customExpression?: string
label?: string
+ tableCalculation?: BITableCalculation
+}
+
+export type BITableCalculationType =
+ | 'percent_of_total'
+ | 'running_total'
+ | 'difference'
+ | 'percent_change'
+ | 'moving_average'
+ | 'rank'
+
+export interface BITableCalculation {
+ type: BITableCalculationType
+ /** Dimension ID to traverse. Unset chooses the date dimension; 'table' traverses all dimensions. */
+ computeUsing?: string
+ /** Number of points, including the current point, in a trailing moving average. */
+ window?: positive_integer
+}
+
+export interface BITopN {
+ fieldId: string
+ count: positive_integer
+ measureIndex: non_negative_integer
+ includeOther: boolean
+}
+
+export interface BITotals {
+ rows?: boolean
+ columns?: boolean
+ subtotals?: boolean
}
export interface BIFilter {
@@ -92,4 +123,6 @@ export interface BIConfig {
limit: BIQueryLimit
/** null sorts automatically: newest date or highest value first, so top rows survive the LIMIT. */
sort?: BISort | null
+ topN?: BITopN
+ totals?: BITotals
}
diff --git a/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx b/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx
index 0ccc0176a071..d570b7fea6b3 100644
--- a/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx
@@ -1058,3 +1058,56 @@ export const BIConnections: Story = {
await waitFor(() => expect(canvas.getByText('annual_revenue')).toBeVisible())
},
}
+
+const BI_ANALYSIS_CONFIG: BIConfig = {
+ ...BI_WORKSHEET_CONFIG,
+ chartType: ChartDisplayType.ActionsTable,
+ values: [
+ { field: biEventsField('revenue', 'float'), aggregation: 'sum', tableCalculation: { type: 'running_total' } },
+ { field: biEventsField('revenue', 'float'), aggregation: 'average' },
+ ],
+ topN: { fieldId: biEventsField('event', 'string').id, count: 5, measureIndex: 0, includeOther: true },
+ totals: { rows: true, subtotals: true },
+}
+
+export const BITableAnalysis: Story = {
+ ...BIModeWorksheet,
+ parameters: {
+ ...BIModeWorksheet.parameters,
+ pageUrl: `${urls.businessIntelligence()}#${new URLSearchParams({
+ q: buildBIQuery(BI_ANALYSIS_CONFIG)!.query,
+ mode: 'bi',
+ bi: JSON.stringify(BI_ANALYSIS_CONFIG),
+ })}`,
+ msw: {
+ mocks: {
+ ...BIModeWorksheet.parameters?.msw.mocks,
+ post: {
+ ...BIModeWorksheet.parameters?.msw.mocks.post,
+ '/api/environments/:team_id/query/HogQLQuery/': {
+ columns: ['bi_row_timestamp', 'bi_column_event', 'sum_revenue', 'average_revenue_2'],
+ types: [
+ ['bi_row_timestamp', 'String'],
+ ['bi_column_event', 'String'],
+ ['sum_revenue', 'Nullable(Float64)'],
+ ['average_revenue_2', 'Float64'],
+ ],
+ results: [
+ ['Total', 'Total', null, 14.2],
+ ['2026-06-01', 'purchase', 120, 12],
+ ['2026-06-02', 'purchase', 300, 15],
+ ['2026-06-01', 'Other', 40, 10],
+ ],
+ hasMore: false,
+ },
+ },
+ },
+ },
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement)
+ await waitFor(() => expect(canvasElement.querySelector('[data-attr="bi-editor-data-source"]')).toBeVisible())
+ await userEvent.click(await canvas.findByRole('button', { name: /^Run$/ }))
+ await waitFor(() => expect(canvas.getAllByText('Total').length).toBeGreaterThan(0))
+ },
+}
diff --git a/posthog/hogql/functions/mapping.py b/posthog/hogql/functions/mapping.py
index 4dde2fd714bc..009522ea51f9 100644
--- a/posthog/hogql/functions/mapping.py
+++ b/posthog/hogql/functions/mapping.py
@@ -219,6 +219,7 @@ HOGQL_CLICKHOUSE_FUNCTIONS: dict[str, HogQLFunctionMeta] = {
"LpNormalize": HogQLFunctionMeta("LpNormalize", 2, 2),
"cosineDistance": HogQLFunctionMeta("cosineDistance", 2, 2),
# window functions
+ "grouping": HogQLFunctionMeta("grouping", 1, None, signatures=[((UnknownType(),), IntegerType())]),
"rank": HogQLFunctionMeta("rank"),
"dense_rank": HogQLFunctionMeta("dense_rank"),
"row_number": HogQLFunctionMeta("row_number"),
diff --git a/posthog/hogql/printer/postgres_functions.py b/posthog/hogql/printer/postgres_functions.py
index 63d4692fd9fe..a3424a629eb7 100644
--- a/posthog/hogql/printer/postgres_functions.py
+++ b/posthog/hogql/printer/postgres_functions.py
@@ -393,6 +393,7 @@ POSTGRES_PASSTHROUGH_FUNCTIONS: frozenset[str] = frozenset(
"row_number",
"rank",
"dense_rank",
+ "grouping",
"lag",
"lead",
"first_value",
diff --git a/posthog/hogql/printer/test/test_printer.py b/posthog/hogql/printer/test/test_printer.py
index 0a3cd0e5bd28..5e9a2aeecfdf 100644
--- a/posthog/hogql/printer/test/test_printer.py
+++ b/posthog/hogql/printer/test/test_printer.py
@@ -2847,6 +2847,11 @@ class TestPrinter(BaseTest):
"select event, distinct_id, count() as c from events group by grouping sets ((event), (distinct_id), ())",
"GROUP BY GROUPING SETS ((events.event), (events.distinct_id), ())",
),
+ (
+ "grouping_mask",
+ "select grouping(event, distinct_id) as mask, count() as c from events group by grouping sets ((event), (distinct_id), ())",
+ "grouping(events.event, events.distinct_id) AS mask",
+ ),
(
"cube",
"select event, distinct_id, count() as c from events group by cube(event, distinct_id)",
diff --git a/posthog/hogql/printer/trino_functions.py b/posthog/hogql/printer/trino_functions.py
index f3bc9da42995..3d42da346398 100644
--- a/posthog/hogql/printer/trino_functions.py
+++ b/posthog/hogql/printer/trino_functions.py
@@ -2100,6 +2100,7 @@ TRINO_PASSTHROUGH_FUNCTIONS = frozenset(
"exp",
"floor",
"greatest",
+ "grouping",
"json_value",
"lag",
"lead",
diff --git a/posthog/schema.py b/posthog/schema.py
index b33e8b7a90d8..7ff266de8945 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -65,6 +65,7 @@ from posthog.schema_enums import (
BingAdsDefaultSources as BingAdsDefaultSources,
BIQueryLimit as BIQueryLimit,
BISortDirection as BISortDirection,
+ BITableCalculationType as BITableCalculationType,
BounceRatePageViewMode as BounceRatePageViewMode,
Breakdown1 as Breakdown1,
BreakdownAttributionType as BreakdownAttributionType,
@@ -952,6 +953,15 @@ class BIDataSource(BaseModel):
table: str
+class BITotals(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ columns: bool | None = None
+ rows: bool | None = None
+ subtotals: bool | None = None
+
+
class BaseAssistantMessage(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -5010,6 +5020,31 @@ class BISort(BaseModel):
key: str
+class BITableCalculation(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ computeUsing: str | None = Field(
+ default=None,
+ description=("Dimension ID to traverse. Unset chooses the date dimension; 'table' traverses all dimensions."),
+ )
+ type: BITableCalculationType
+ window: conint(ge=1) | None = Field(
+ default=None,
+ description=("Number of points, including the current point, in a trailing moving average."),
+ )
+
+
+class BITopN(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ count: conint(ge=1)
+ fieldId: str
+ includeOther: bool
+ measureIndex: conint(ge=0)
+
+
class BIValue(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -5018,6 +5053,7 @@ class BIValue(BaseModel):
customExpression: str | None = None
field: BIField
label: str | None = None
+ tableCalculation: BITableCalculation | None = None
class BoxPlotDatum(BaseModel):
@@ -11085,6 +11121,8 @@ class BIConfig(BaseModel):
description=("null sorts automatically: newest date or highest value first, so top rows survive the LIMIT."),
)
source: BIDataSource | None = None
+ topN: BITopN | None = None
+ totals: BITotals | None = None
values: list[BIValue]
diff --git a/posthog/schema_enums.py b/posthog/schema_enums.py
index df6b0a2069d8..c922c8d60d3c 100644
--- a/posthog/schema_enums.py
+++ b/posthog/schema_enums.py
@@ -668,6 +668,15 @@ class BISortDirection(StrEnum):
DESC = "desc"
+class BITableCalculationType(StrEnum):
+ PERCENT_OF_TOTAL = "percent_of_total"
+ RUNNING_TOTAL = "running_total"
+ DIFFERENCE = "difference"
+ PERCENT_CHANGE = "percent_change"
+ MOVING_AVERAGE = "moving_average"
+ RANK = "rank"
+
+
class BaseMathType(StrEnum):
TOTAL = "total"
DAU = "dau"
diff --git a/products/business_intelligence/frontend/BIAnalysisControls.tsx b/products/business_intelligence/frontend/BIAnalysisControls.tsx
new file mode 100644
index 000000000000..e36cdbb4cfc6
--- /dev/null
+++ b/products/business_intelligence/frontend/BIAnalysisControls.tsx
@@ -0,0 +1,107 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonCheckbox, LemonInput, LemonLabel, LemonSelect } from '@posthog/lemon-ui'
+
+import { ChartDisplayType } from '~/types'
+
+import { biEditorLogic } from './biEditorLogic'
+import { getBIValuePillLabel, isDateTimeBIField } from './biEditorTypes'
+import { BIShelfCard } from './components/BIShelfCard'
+
+export function BIAnalysisControls(): JSX.Element {
+ const { config } = useValues(biEditorLogic)
+ const { setTopN, setTotals } = 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">
+ <LemonCheckbox
+ label="Top N breakdown"
+ checked={!!config.topN}
+ disabledReason={!dimensions.length ? 'Add a categorical dimension first' : undefined}
+ onChange={(checked) =>
+ setTopN(
+ checked
+ ? { fieldId: dimensions[0].id, count: 10, measureIndex: 0, includeOther: true }
+ : undefined
+ )
+ }
+ />
+ {config.topN ? (
+ <>
+ <LemonSelect
+ size="xsmall"
+ fullWidth
+ aria-label="Top N dimension"
+ value={config.topN.fieldId}
+ options={dimensions.map((field) => ({ value: field.id, label: field.name }))}
+ onChange={(fieldId) => setTopN({ ...config.topN!, fieldId })}
+ />
+ <LemonInput
+ size="small"
+ type="number"
+ min={1}
+ max={100}
+ aria-label="Top N count"
+ value={config.topN.count}
+ onChange={(count) =>
+ setTopN({ ...config.topN!, count: Math.max(1, Math.min(100, Math.trunc(count ?? 10))) })
+ }
+ />
+ <LemonSelect
+ size="xsmall"
+ fullWidth
+ aria-label="Rank breakdown by"
+ value={config.topN.measureIndex}
+ options={
+ config.values.length
+ ? config.values.map((value, index) => ({
+ value: index,
+ label: getBIValuePillLabel(value),
+ }))
+ : [{ value: 0, label: 'Count' }]
+ }
+ onChange={(measureIndex) => setTopN({ ...config.topN!, measureIndex })}
+ />
+ <LemonCheckbox
+ label='Include "Other"'
+ checked={config.topN.includeOther}
+ onChange={(includeOther) => setTopN({ ...config.topN!, includeOther })}
+ />
+ <span className="text-xs text-secondary">
+ Ranked across the full date range before table calculations.
+ </span>
+ </>
+ ) : null}
+ {table ? (
+ <>
+ <LemonLabel>Totals</LemonLabel>
+ <LemonCheckbox
+ label={
+ config.chartType === ChartDisplayType.ActionsTable ? 'Grand total' : 'Row grand totals'
+ }
+ checked={!!config.totals?.rows}
+ onChange={(rows) => setTotals({ ...config.totals, rows })}
+ />
+ {config.chartType === ChartDisplayType.TwoDimensionalHeatmap ? (
+ <LemonCheckbox
+ label="Column grand totals"
+ checked={!!config.totals?.columns}
+ onChange={(columns) => setTotals({ ...config.totals, columns })}
+ />
+ ) : null}
+ <LemonCheckbox
+ label="Subtotals"
+ checked={!!config.totals?.subtotals}
+ onChange={(subtotals) => setTotals({ ...config.totals, subtotals })}
+ />
+ {config.values.some((value) => value.tableCalculation) ? (
+ <span className="text-xs text-secondary">Table calculation cells are blank in totals.</span>
+ ) : null}
+ </>
+ ) : null}
+ </div>
+ </BIShelfCard>
+ )
+}
diff --git a/products/business_intelligence/frontend/BIEditor.tsx b/products/business_intelligence/frontend/BIEditor.tsx
index 11834b5546d3..235f5d04a0b3 100644
--- a/products/business_intelligence/frontend/BIEditor.tsx
+++ b/products/business_intelligence/frontend/BIEditor.tsx
@@ -20,6 +20,8 @@ import { BIShelfStrip } from 'products/business_intelligence/frontend/components
import { BIShowMe } from 'products/business_intelligence/frontend/components/BIShowMe'
import { BIToolbar } from 'products/business_intelligence/frontend/components/BIToolbar'
+import { BIAnalysisControls } from './BIAnalysisControls'
+
/**
* A worksheet laid out like desktop BI tools: data pane, filter and marks cards, rows and columns
* shelves above the view, and a chart picker on the right.
@@ -71,6 +73,7 @@ export function BIEditor({ tabId, children }: { tabId: string; children: ReactNo
<div className="flex max-h-[40%] shrink-0 flex-col overflow-y-auto border-t @5xl/bi-editor:max-h-none @5xl/bi-editor:w-40 @5xl/bi-editor:border-l @5xl/bi-editor:border-t-0">
<BIFiltersCard />
<BIMarksCard />
+ <BIAnalysisControls />
</div>
<Resizer {...biEditorResizerProps} />
</div>
diff --git a/products/business_intelligence/frontend/BIMeasureAnalysis.tsx b/products/business_intelligence/frontend/BIMeasureAnalysis.tsx
new file mode 100644
index 000000000000..638d56e92373
--- /dev/null
+++ b/products/business_intelligence/frontend/BIMeasureAnalysis.tsx
@@ -0,0 +1,69 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonInput, LemonLabel, LemonSelect } from '@posthog/lemon-ui'
+
+import { BI_TABLE_CALCULATIONS } from './biAnalysis'
+import { biEditorLogic } from './biEditorLogic'
+import { getBIValuePillLabel } from './biEditorTypes'
+
+export function BIMeasureAnalysis({ index }: { index: number }): JSX.Element {
+ const { config } = useValues(biEditorLogic)
+ const { setTableCalculation } = useActions(biEditorLogic)
+ const value = config.values[index]
+ const calculation = value.tableCalculation
+ return (
+ <div className="flex min-w-0 flex-col gap-1 border-t pt-2">
+ <LemonLabel className="truncate">{getBIValuePillLabel(value)}</LemonLabel>
+ <LemonSelect
+ size="xsmall"
+ fullWidth
+ aria-label={`Calculation for ${getBIValuePillLabel(value)}`}
+ data-attr="bi-editor-table-calculation"
+ value={calculation?.type ?? null}
+ options={[{ value: null, label: 'No table calculation' }, ...BI_TABLE_CALCULATIONS]}
+ onChange={(type) => setTableCalculation(index, type ? { ...calculation, type } : undefined)}
+ />
+ {calculation ? (
+ <>
+ <LemonSelect
+ size="xsmall"
+ fullWidth
+ aria-label="Compute using"
+ value={calculation.computeUsing ?? null}
+ options={[
+ { value: null, label: 'Automatic (date first)' },
+ { value: 'table', label: 'Entire table' },
+ ...[...config.rows, ...config.columns].map((field) => ({
+ value: field.id,
+ label: field.name,
+ })),
+ ]}
+ onChange={(computeUsing) =>
+ setTableCalculation(index, { ...calculation, computeUsing: computeUsing ?? undefined })
+ }
+ />
+ {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))),
+ })
+ }
+ />
+ ) : null}
+ <span className="text-xs text-secondary">
+ Ascending order within each series. Missing points stay missing.
+ </span>
+ </>
+ ) : null}
+ </div>
+ )
+}
diff --git a/products/business_intelligence/frontend/biAnalysis.test.ts b/products/business_intelligence/frontend/biAnalysis.test.ts
new file mode 100644
index 000000000000..d4ac1e03b167
--- /dev/null
+++ b/products/business_intelligence/frontend/biAnalysis.test.ts
@@ -0,0 +1,144 @@
+import { BIConfig, BIField } from '~/queries/schema/schema-business-intelligence'
+import { ChartDisplayType } from '~/types'
+
+import { BI_TABLE_CALCULATIONS } from './biAnalysis'
+import { BIEditorView, buildBIQuery, DEFAULT_BI_CONFIG, parseBIEditorState } 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' },
+ rows: [{ ...field('timestamp', 'datetime'), dateBucket: 'day' }],
+ columns: [field('event')],
+ values: [{ field: field('properties.amount', 'float'), aggregation: 'sum' }],
+}
+
+describe('BI analysis queries', () => {
+ it.each(BI_TABLE_CALCULATIONS)('persists and calculates $value before limiting results', ({ value: type }) => {
+ const worksheet: BIConfig = {
+ ...config,
+ values: [{ ...config.values[0], tableCalculation: { type, window: 7 } }],
+ }
+ const parsed = parseBIEditorState(BIEditorView.BI, JSON.stringify(worksheet))!.config
+ expect(parsed.values[0].tableCalculation).toEqual({ type, window: 7 })
+ const result = buildBIQuery(parsed)!
+ expect(result.query).toMatch(new RegExp(`LIMIT ${worksheet.limit}$`))
+ expect(buildBIQuery(parsed, true)!.query).toMatch(new RegExp(`LIMIT ${worksheet.limit + 1}$`))
+ expect(result.query).toContain('OVER (PARTITION BY bi_column_event')
+ expect(result.query.match(/LIMIT/g)).toHaveLength(1)
+ if (type === 'percent_change' || type === 'percent_of_total') {
+ expect(result.query).toContain('nullIf(')
+ expect(result.node.tableSettings?.columns?.map((column) => column.column)).toEqual([
+ 'bi_row_timestamp',
+ 'bi_column_event',
+ 'sum_properties_amount',
+ ])
+ expect(result.node.tableSettings?.columns?.[2].settings?.formatting?.style).toBe('percent')
+ }
+ if (type === 'moving_average') {
+ expect(result.query).toContain('6 PRECEDING AND CURRENT ROW')
+ }
+ if (type === 'running_total') {
+ expect(result.query).toContain('ORDER BY bi_row_timestamp ASC ROWS')
+ }
+ const across = buildBIQuery({
+ ...worksheet,
+ values: [{ ...worksheet.values[0], tableCalculation: { type, computeUsing: 'table' } }],
+ })!
+ expect(across.query).not.toContain('PARTITION BY bi_column_event')
+ })
+
+ it.each(['average', 'count_distinct'] as const)('reaggregates %s for Other and totals', (aggregation) => {
+ const worksheet: BIConfig = {
+ ...config,
+ chartType: ChartDisplayType.TwoDimensionalHeatmap,
+ values: [{ field: field('properties.amount', 'float'), aggregation }],
+ topN: { fieldId: 'event', count: 5, measureIndex: 0, includeOther: true },
+ totals: { rows: true, columns: true, subtotals: true },
+ }
+ const result = buildBIQuery(worksheet)!
+ expect(result.query).toContain('GROUP BY bi_key ORDER BY')
+ expect(result.query).toContain(
+ 'GROUPING SETS ((bi_row_timestamp, bi_column_event), (bi_row_timestamp), (bi_column_event), ())'
+ )
+ 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(parseBIEditorState(BIEditorView.BI, worksheet)?.config.topN).toEqual(worksheet.topN)
+ expect(parseBIEditorState(BIEditorView.BI, worksheet)?.config.totals).toEqual(worksheet.totals)
+ })
+
+ it('reserves detail rows and sorts numeric dimensions before their total labels are formatted', () => {
+ const result = buildBIQuery({
+ ...config,
+ chartType: ChartDisplayType.ActionsTable,
+ limit: 100,
+ rows: [field('number', 'integer')],
+ totals: { rows: true, columns: true },
+ sort: { key: 'rows:number', direction: 'asc' },
+ })!
+ expect(result.query).toContain('PARTITION BY bi_grouping = 0')
+ expect(result.query).toContain('GROUPING SETS ((bi_row_number, bi_column_event), ())')
+ expect(result.query).toContain('WHERE bi_grouping = 0 OR bi_rank <= 50')
+ expect(result.query).toContain('ORDER BY bi_grouping DESC, bi_result.bi_row_number ASC LIMIT 100')
+ const probe = buildBIQuery(
+ { ...config, chartType: ChartDisplayType.ActionsTable, limit: 100, totals: { rows: true } },
+ true
+ )!
+ expect(probe.query).toContain('WHERE bi_grouping = 0 OR bi_rank <= 50')
+ expect(probe.query).toMatch(/LIMIT 101$/)
+ })
+
+ it('probes beyond the combined comparison limit without changing the saved query', () => {
+ const worksheet: BIConfig = {
+ ...config,
+ limit: 100,
+ dateRange: { date_from: '-7d' },
+ compareFilter: { compare: true },
+ }
+ const saved = buildBIQuery(worksheet)!
+ const probe = buildBIQuery(worksheet, true)!
+ expect(saved.query).toMatch(/^SELECT \* FROM \(/)
+ 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$/)
+ })
+
+ it.each([undefined, '-1y'])(
+ 'keeps period windows independent and shares the current-period Top N (%s)',
+ (compare_to) => {
+ const result = buildBIQuery({
+ ...config,
+ dateRange: { date_from: '-7d' },
+ compareFilter: { compare: true, compare_to },
+ topN: { fieldId: 'event', count: 5, measureIndex: 0, includeOther: false },
+ values: [{ ...config.values[0], tableCalculation: { type: 'running_total' } }],
+ })!
+ expect(result.query).toContain('{filters.previous}')
+ expect(result.query).toContain('{filters.compareDate(timestamp)}')
+ expect(result.query).toContain('FROM bi_previous')
+ expect(result.query.match(/FROM bi_top/g)).toHaveLength(4)
+ expect(result.query).toContain(`'${compare_to ? 'Comparison period' : 'Previous period'}' AS bi_period`)
+ }
+ )
+
+ it.each([
+ { topN: { fieldId: 'event', count: -1, measureIndex: 0, includeOther: true } },
+ { totals: { rows: 'true' } },
+ {
+ values: [
+ { ...config.values[0], tableCalculation: { type: 'moving_average', window: '7); DROP TABLE events' } },
+ ],
+ },
+ ])('rejects malformed analysis settings %j', (invalid) => {
+ expect(parseBIEditorState(BIEditorView.BI, { ...config, ...invalid })).toBeNull()
+ })
+})
diff --git a/products/business_intelligence/frontend/biAnalysis.ts b/products/business_intelligence/frontend/biAnalysis.ts
new file mode 100644
index 000000000000..a11216c84302
--- /dev/null
+++ b/products/business_intelligence/frontend/biAnalysis.ts
@@ -0,0 +1,260 @@
+import { BIConfig, BIField, BITableCalculation, BIValue } from '~/queries/schema/schema-business-intelligence'
+import { escapeHogQLString, escapeRawPropertyAsHogQLIdentifier } from '~/queries/utils'
+import { ChartDisplayType } from '~/types'
+
+export const BI_TABLE_CALCULATIONS: { value: BITableCalculation['type']; label: string }[] = [
+ { value: 'percent_of_total', label: 'Percent of total' },
+ { value: 'running_total', label: 'Running total' },
+ { value: 'difference', label: 'Change from previous point' },
+ { value: 'percent_change', label: 'Percent change from previous point' },
+ { value: 'moving_average', label: 'Moving average' },
+ { value: 'rank', label: 'Rank' },
+]
+
+export function isBITableCalculation(value: unknown): value is BITableCalculation {
+ if (!value || typeof value !== 'object') {
+ return false
+ }
+ const candidate = value as BITableCalculation
+ return (
+ BI_TABLE_CALCULATIONS.some(({ value }) => value === candidate.type) &&
+ (candidate.computeUsing === undefined || typeof candidate.computeUsing === 'string') &&
+ (candidate.window === undefined ||
+ (Number.isInteger(candidate.window) && candidate.window >= 1 && candidate.window <= 1000))
+ )
+}
+
+export function isBIAnalysisConfig(config: Partial<BIConfig>): boolean {
+ const top = config.topN
+ const totals = config.totals
+ return (
+ (top === undefined ||
+ (!!top &&
+ typeof top === 'object' &&
+ typeof top.fieldId === 'string' &&
+ Number.isInteger(top.count) &&
+ top.count >= 1 &&
+ top.count <= 100 &&
+ Number.isInteger(top.measureIndex) &&
+ top.measureIndex >= 0 &&
+ typeof top.includeOther === 'boolean')) &&
+ (totals === undefined ||
+ (!!totals &&
+ typeof totals === 'object' &&
+ [totals.rows, totals.columns, totals.subtotals].every(
+ (value) => value === undefined || typeof value === 'boolean'
+ )))
+ )
+}
+
+export interface BIAnalysisDimension {
+ field: BIField
+ alias: string
+ expression: string
+}
+
+export interface BIAnalysisMeasure {
+ value?: BIValue
+ alias: string
+ expression: string
+}
+
+export interface BIAnalysisInput {
+ rows: BIAnalysisDimension[]
+ columns: BIAnalysisDimension[]
+ measures: BIAnalysisMeasure[]
+ from: string
+ where: string
+ orderBy: string | null
+ resultLimit?: number
+ previousWhere?: string
+ previousDimensions?: string[]
+}
+
+export function hasBIAnalysis(config: BIConfig): boolean {
+ return (
+ !!config.topN ||
+ config.values.some((value) => !!value.tableCalculation) ||
+ !!(config.totals?.rows || config.totals?.columns || config.totals?.subtotals)
+ )
+}
+
+function calculationExpression(
+ measure: BIAnalysisMeasure,
+ dimensions: BIAnalysisDimension[],
+ partition: string[]
+): string {
+ const column = escapeRawPropertyAsHogQLIdentifier(measure.alias)
+ const calc = measure.value?.tableCalculation
+ if (!calc) {
+ return column
+ }
+ const axis =
+ dimensions.find((dimension) => dimension.field.id === calc.computeUsing) ??
+ dimensions.find((dimension) => ['date', 'datetime'].includes(dimension.field.type)) ??
+ dimensions[0]
+ const across = calc.computeUsing === 'table' ? dimensions : axis ? [axis] : []
+ const within = [
+ ...partition,
+ ...dimensions.filter((dimension) => !across.includes(dimension)).map((dimension) => dimension.alias),
+ ]
+ const partitionBy = within.length ? `PARTITION BY ${within.join(', ')} ` : ''
+ const order = across.length ? across.map((dimension) => `${dimension.alias} ASC`).join(', ') : column
+ const window = `${partitionBy}ORDER BY ${order}`
+ const previous = `lag(${column}, 1, NULL) OVER (${window})`
+ switch (calc.type) {
+ case 'percent_of_total':
+ return `${column} * 1.0 / nullIf(sum(${column}) OVER (${partitionBy.trim()}), 0)`
+ case 'running_total':
+ return `sum(${column}) OVER (${window} ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)`
+ case 'difference':
+ 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 'rank':
+ return `rank() OVER (${partitionBy}ORDER BY ${column} DESC)`
+ }
+}
+
+function groupingSets(config: BIConfig, input: BIAnalysisInput): string[][] {
+ const rows = input.rows.map((dimension) => dimension.alias)
+ const columns = input.columns.map((dimension) => dimension.alias)
+ const sets = [[...rows, ...columns]]
+ if (![ChartDisplayType.ActionsTable, ChartDisplayType.TwoDimensionalHeatmap].includes(config.chartType)) {
+ return sets
+ }
+ const pivot = config.chartType === ChartDisplayType.TwoDimensionalHeatmap
+ if (pivot && config.totals?.rows) {
+ sets.push(rows)
+ }
+ if (pivot && config.totals?.columns) {
+ sets.push(columns)
+ }
+ if (config.totals?.rows || config.totals?.columns) {
+ sets.push([])
+ }
+ if (config.totals?.subtotals) {
+ for (let length = 1; length < rows.length; length++) {
+ sets.push([...rows.slice(0, length), ...columns])
+ }
+ for (let length = 1; length < columns.length; length++) {
+ sets.push([...rows, ...columns.slice(0, length)])
+ }
+ }
+ 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 ctes: string[] = []
+ const topMeasure = config.values.length
+ ? input.measures.find((measure) => measure.value === config.values[config.topN?.measureIndex ?? 0])
+ : input.measures[0]
+ const topDimension = topMeasure && dimensions.find((dimension) => dimension.field.id === config.topN?.fieldId)
+ if (config.topN && topDimension && topMeasure) {
+ ctes.push(
+ `bi_top AS (SELECT ${topDimension.expression} AS bi_key FROM ${input.from} WHERE ${input.where} GROUP BY bi_key ORDER BY ${topMeasure.expression} DESC, bi_key ASC LIMIT ${Math.max(1, Math.min(100, Math.trunc(config.topN.count)))})`
+ )
+ }
+ const sets = groupingSets(config, input)
+ const totals = sets.length > 1
+ const aliases = dimensions.map((dimension) => dimension.alias)
+ const groupingFlags = dimensions.map((_, index) => `bi_grouping_${index}`)
+ const periods = input.previousWhere ? [false, true] : [false]
+ const topMember = topDimension
+ ? `(${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) => {
+ 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}`
+ })
+ const where = previous ? input.previousWhere! : input.where
+ const topFilter = config.topN && topDimension && !config.topN.includeOther ? ` AND ${topMember}` : ''
+ const select = [
+ ...projection,
+ ...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]}`),
+ ]
+ : []),
+ ]
+ 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 calculations = input.measures.map((measure) => {
+ const expression = calculationExpression(measure, dimensions, totals ? ['bi_grouping'] : [])
+ return `${totals && measure.value?.tableCalculation ? `if(bi_grouping = 0, ${expression}, NULL)` : expression} AS ${escapeRawPropertyAsHogQLIdentifier(measure.alias)}`
+ })
+ 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'}`
+ ctes.push(`bi_calculated AS (${periods.map(periodQuery).join(' UNION ALL ')})`)
+ const displayedDimension = (dimension: BIAnalysisDimension, index: number): string => {
+ let expression = dimension.alias
+ 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 displayed = dimensions.map(displayedDimension)
+ const pivot = config.chartType === ChartDisplayType.TwoDimensionalHeatmap
+ const axis = (side: 'rows' | 'columns'): string[] => {
+ const fields = input[side]
+ if (!fields.length) {
+ return []
+ }
+ const expressions = fields.map((field) => displayed[dimensions.indexOf(field)])
+ return [
+ `${expressions.length === 1 ? expressions[0] : `toJSONString(tuple(${expressions.join(', ')}))`} AS ${fields.length === 1 ? fields[0].alias : `bi_${side}`}`,
+ ]
+ }
+ const select = [
+ ...(pivot
+ ? [...axis('rows'), ...axis('columns')]
+ : dimensions.map((dimension, index) => `${displayed[index]} AS ${dimension.alias}`)),
+ ...input.measures.map((measure) => escapeRawPropertyAsHogQLIdentifier(measure.alias)),
+ ]
+ if (input.previousWhere) {
+ const xDimension =
+ dimensions.find((dimension) => ['date', 'datetime'].includes(dimension.field.type)) ??
+ input.columns[0] ??
+ 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`
+ )
+ }
+ let order = input.orderBy
+ for (const dimension of dimensions) {
+ if (order === `${dimension.expression} ASC` || order === `${dimension.expression} DESC`) {
+ order = `${dimension.alias} ${order.endsWith(' ASC') ? 'ASC' : 'DESC'}`
+ }
+ }
+ if (totals) {
+ // Reserve at least half the result budget for detail cells when summaries alone exceed it.
+ ctes.push(
+ `bi_ranked AS (SELECT *, row_number() OVER (PARTITION BY bi_grouping = 0 ORDER BY bi_grouping DESC${order ? `, ${order}` : ''}) AS bi_rank FROM bi_calculated)`
+ )
+ }
+ for (const { alias } of dimensions) {
+ if (order === `${alias} ASC` || order === `${alias} DESC`) {
+ order = `bi_result.${order}`
+ break
+ }
+ }
+ return `WITH ${ctes.join(',\n')}\nSELECT ${select.join(', ')} FROM ${totals ? 'bi_ranked' : 'bi_calculated'} AS bi_result${totals ? ` WHERE bi_grouping = 0 OR bi_rank <= ${Math.floor(config.limit / 2)}` : ''}${totals || order ? ` ORDER BY ${[...(totals ? ['bi_grouping DESC'] : []), ...(order ? [order] : [])].join(', ')}` : ''} LIMIT ${input.resultLimit ?? config.limit}`
+}
diff --git a/products/business_intelligence/frontend/biEditorLogic.test.ts b/products/business_intelligence/frontend/biEditorLogic.test.ts
index 82b50e05c9c0..b7e0aadddae2 100644
--- a/products/business_intelligence/frontend/biEditorLogic.test.ts
+++ b/products/business_intelligence/frontend/biEditorLogic.test.ts
@@ -51,6 +51,31 @@ describe('biEditorLogic', () => {
limit: 1000,
sort: null,
}
+ it.each([0, 1, 2])('keeps Top N attached to its measure when removing value %s', (index) => {
+ const logic = biEditorLogic({ tabId: TAB_ID })
+ logic.mount()
+ logic.actions.setAutoUpdate(false)
+ logic.actions.restoreState({
+ editorView: BIEditorView.BI,
+ config: {
+ ...config,
+ values: [0, 1, 2].map((value) => ({
+ field: { ...eventField, id: `measure-${value}`, expression: `properties.value_${value}` },
+ aggregation: 'sum',
+ })),
+ topN: { fieldId: eventField.id, count: 5, measureIndex: 1, includeOther: false },
+ },
+ })
+ logic.actions.removeFieldFromShelf('values', index)
+ if (index === 1) {
+ expect(logic.values.config.topN).toBeUndefined()
+ } else {
+ const measureIndex = logic.values.config.topN!.measureIndex
+ expect(logic.values.config.values[measureIndex].field.id).toBe('measure-1')
+ }
+ logic.unmount()
+ })
+
it('offers every sidebar table while excluding hidden PostHog tables', () => {
const biLogic = biEditorLogic({ tabId: TAB_ID })
biLogic.mount()
diff --git a/products/business_intelligence/frontend/biEditorLogic.ts b/products/business_intelligence/frontend/biEditorLogic.ts
index 786de61ddbc6..c2d71def12fa 100644
--- a/products/business_intelligence/frontend/biEditorLogic.ts
+++ b/products/business_intelligence/frontend/biEditorLogic.ts
@@ -12,6 +12,9 @@ import {
BIField,
BIFilter,
BIFilterOperator,
+ BITableCalculation,
+ BITopN,
+ BITotals,
BIQueryLimit,
BISort,
} from '~/queries/schema/schema-business-intelligence'
@@ -171,7 +174,20 @@ function removeFieldFromConfig(config: BIConfig, shelf: BIShelf, index: number):
case 'columns':
return { ...config, [shelf]: config[shelf].filter((_, fieldIndex) => fieldIndex !== index) }
case 'values':
- return { ...config, values: config.values.filter((_, valueIndex) => valueIndex !== index) }
+ return {
+ ...config,
+ values: config.values.filter((_, valueIndex) => valueIndex !== index),
+ topN:
+ !config.topN || config.topN.measureIndex === index
+ ? undefined
+ : {
+ ...config.topN,
+ measureIndex:
+ config.topN.measureIndex > index
+ ? config.topN.measureIndex - 1
+ : config.topN.measureIndex,
+ },
+ }
case 'filters':
return { ...config, filters: config.filters.filter((_, filterIndex) => filterIndex !== index) }
}
@@ -192,6 +208,7 @@ function setFieldExpressionInConfig(config: BIConfig, shelf: BIShelf, index: num
values: config.values.map((value, valueIndex) =>
valueIndex === index ? { ...value, field: updateField(value.field) } : value
),
+ topN: config.topN?.measureIndex === index ? undefined : config.topN,
}
case 'filters':
return {
@@ -417,6 +434,19 @@ export interface biEditorLogicActions {
setSort: (sort: BISort | null) => {
sort: BISort | null
}
+ setTableCalculation: (
+ index: number,
+ tableCalculation: BITableCalculation | undefined
+ ) => {
+ index: number
+ tableCalculation: BITableCalculation | undefined
+ }
+ setTopN: (topN: BITopN | undefined) => {
+ topN: BITopN | undefined
+ }
+ setTotals: (totals: BITotals) => {
+ totals: BITotals
+ }
setValueAggregation: (
index: number,
aggregation: BIAggregation
@@ -537,6 +567,12 @@ export const biEditorLogic = kea<biEditorLogicType>([
setDateField: (field: BIField | null) => ({ field }),
setDataSource: (source: BIDataSource) => ({ source }),
setValueAggregation: (index: number, aggregation: BIAggregation) => ({ index, aggregation }),
+ setTableCalculation: (index: number, tableCalculation: BITableCalculation | undefined) => ({
+ index,
+ tableCalculation,
+ }),
+ setTopN: (topN: BITopN | undefined) => ({ topN }),
+ setTotals: (totals: BITotals) => ({ totals }),
setFilterOperator: (index: number, operator: BIFilterOperator) => ({ index, operator }),
setFilterValue: (index: number, value: string) => ({ index, value }),
updateFilter: (index: number, update: Partial<Pick<BIFilter, 'values' | 'valueTo' | 'enabled'>>) => ({
@@ -664,6 +700,14 @@ export const biEditorLogic = kea<biEditorLogicType>([
valueIndex === index ? { ...value, aggregation } : value
),
}),
+ setTableCalculation: (config, { index, tableCalculation }) => ({
+ ...config,
+ values: config.values.map((value, valueIndex) =>
+ valueIndex === index ? { ...value, tableCalculation } : value
+ ),
+ }),
+ setTopN: (config, { topN }) => ({ ...config, topN }),
+ setTotals: (config, { totals }) => ({ ...config, totals }),
setFilterOperator: (config, { index, operator }) => ({
...config,
filters: config.filters.map((filter, filterIndex) =>
@@ -848,6 +892,9 @@ export const biEditorLogic = kea<biEditorLogicType>([
setDateField: () => actions.runAfterChange(),
setDataSource: () => actions.runAfterChange(),
setValueAggregation: () => actions.runAfterChange(),
+ setTableCalculation: () => actions.runAfterChange(),
+ setTopN: () => actions.runAfterChange(),
+ setTotals: () => actions.runAfterChange(),
setFilterOperator: () => actions.runAfterChange(),
setFilterValue: () => actions.runAfterChange(),
updateFilter: () => actions.runAfterChange(),
diff --git a/products/business_intelligence/frontend/biEditorTypes.ts b/products/business_intelligence/frontend/biEditorTypes.ts
index 4acbc4eebe82..288063a689d5 100644
--- a/products/business_intelligence/frontend/biEditorTypes.ts
+++ b/products/business_intelligence/frontend/biEditorTypes.ts
@@ -28,6 +28,13 @@ import {
} from '~/queries/utils'
import { ChartDisplayType } from '~/types'
+import {
+ BI_TABLE_CALCULATIONS,
+ buildBIAnalysisQuery,
+ hasBIAnalysis,
+ isBIAnalysisConfig,
+ isBITableCalculation,
+} from './biAnalysis'
import { getBIComparisonDisabledReason, getBIComparisonDateExpression } from './biComparison'
import { getBIFiltersPlaceholder, getBIQueryFilters, normalizeBIDates } from './biQueryFilters'
@@ -133,6 +140,13 @@ export function normalizeBIConfig(config: BIConfig): BIConfig {
if (sort && !getBISortOptions(normalized).some((option) => option.key === sort.key)) {
normalized = { ...normalized, sort: null }
}
+ if (
+ normalized.topN &&
+ (![...normalized.rows, ...normalized.columns].some((field) => field.id === normalized.topN?.fieldId) ||
+ normalized.topN.measureIndex >= Math.max(1, normalized.values.length))
+ ) {
+ normalized = { ...normalized, topN: undefined }
+ }
return normalized
}
@@ -431,6 +445,9 @@ export function parseBIEditorState(editorViewValue: unknown, configValue: unknow
}
const candidate = decodedConfig as Partial<BIConfig>
+ if (!isBIAnalysisConfig(candidate)) {
+ return null
+ }
if (
candidate.compareFilter !== undefined &&
(!candidate.compareFilter ||
@@ -475,6 +492,8 @@ export function parseBIEditorState(editorViewValue: unknown, configValue: unknow
!field ||
!BI_AGGREGATIONS.has(valueCandidate.aggregation as BIAggregation) ||
(valueCandidate.label !== undefined && typeof valueCandidate.label !== 'string') ||
+ (valueCandidate.tableCalculation !== undefined &&
+ !isBITableCalculation(valueCandidate.tableCalculation)) ||
(valueCandidate.customExpression !== undefined && typeof valueCandidate.customExpression !== 'string')
) {
return null
@@ -484,6 +503,7 @@ export function parseBIEditorState(editorViewValue: unknown, configValue: unknow
aggregation: valueCandidate.aggregation as BIAggregation,
customExpression: valueCandidate.customExpression,
label: valueCandidate.label,
+ ...(valueCandidate.tableCalculation ? { tableCalculation: valueCandidate.tableCalculation } : {}),
}
})
: null
@@ -549,6 +569,8 @@ export function parseBIEditorState(editorViewValue: unknown, configValue: unknow
const config: BIConfig = {
source,
+ ...(candidate.topN ? { topN: candidate.topN } : {}),
+ ...(candidate.totals ? { totals: candidate.totals } : {}),
...(candidate.compareFilter !== undefined ? { compareFilter: candidate.compareFilter } : {}),
...(candidate.dateField !== undefined
? { dateField: candidate.dateField === null ? null : parseBIFieldValue(candidate.dateField) }
@@ -839,7 +861,15 @@ function computeBIQueryParts(config: BIConfig): BIQueryParts {
...configuredValues.map(({ expression }) => expression),
...config.filters.map((filter) => filter.customExpression || fieldExpression(filter.field)),
]
- const usedAliases = new Set(['bi_rows', 'bi_columns', 'bi_comparison'])
+ const usedAliases = new Set([
+ 'bi_rows',
+ 'bi_columns',
+ 'bi_comparison',
+ 'bi_period',
+ 'bi_grouping',
+ 'bi_rank',
+ ...[...rowDimensions, ...columnDimensions].map((_, index) => `bi_grouping_${index}`),
+ ])
for (const dimension of [...rowDimensions, ...columnDimensions]) {
const preferred = dimension.alias
let suffix = 2
@@ -967,6 +997,9 @@ export function getBIFieldPillLabel(field: BIField): string {
}
export function getBIValuePillLabel(value: BIValue): string {
+ if (value.tableCalculation) {
+ return `${BI_TABLE_CALCULATIONS.find((option) => option.value === value.tableCalculation?.type)?.label} · ${getBIValuePillLabel({ ...value, tableCalculation: undefined })}`
+ }
if (value.aggregation === 'custom') {
return value.label?.trim() || value.customExpression?.trim() || 'New calculation'
}
@@ -1000,7 +1033,7 @@ function buildOrderByExpression(
return `${firstValueAlias} DESC`
}
-export function buildBIQuery(config: BIConfig): BIQueryBuildResult | null {
+export function buildBIQuery(config: BIConfig, probeForMoreRows = false): BIQueryBuildResult | null {
config = normalizeBIConfig(config)
if (!config.source || config.filters.some(getBIFilterValidationError)) {
return null
@@ -1027,7 +1060,9 @@ export function buildBIQuery(config: BIConfig): BIQueryBuildResult | null {
.filter((axis): axis is BIPivotAxis => axis !== null)
.map(({ alias, expression }) => `${expression} AS ${alias}`)
: dimensions.map(({ field, alias }) =>
- hasSeriesBreakdown || comparing ? `${fieldExpression(field)} AS ${alias}` : fieldExpression(field)
+ hasSeriesBreakdown || comparing || hasBIAnalysis(config)
+ ? `${fieldExpression(field)} AS ${alias}`
+ : fieldExpression(field)
)
const valueExpressions =
configuredValues.length > 0
@@ -1062,7 +1097,8 @@ export function buildBIQuery(config: BIConfig): BIQueryBuildResult | null {
queryParts.push(`ORDER BY\n ${orderByExpression}`)
}
- queryParts.push(`LIMIT ${normalizeBIConfig(config).limit}`)
+ const resultLimit = normalizeBIConfig(config).limit + (probeForMoreRows ? 1 : 0)
+ queryParts.push(`LIMIT ${resultLimit}`)
let query = queryParts.join('\n')
@@ -1115,10 +1151,10 @@ export function buildBIQuery(config: BIConfig): BIQueryBuildResult | null {
`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 ${config.limit}`,
+ `LIMIT ${resultLimit}`,
].join('\n')
}
- query = `(${buildPeriod(false)})\nUNION ALL\n(${buildPeriod(true)})`
+ query = `SELECT * FROM ((${buildPeriod(false)})\nUNION ALL\n(${buildPeriod(true)})) LIMIT ${resultLimit}`
seriesSettings = {
xAxis: { column: xDimension?.alias ?? 'bi_comparison' },
xAxisLabel: xDimension ? getBIFieldPillLabel(xDimension.field) : 'Period',
@@ -1142,6 +1178,64 @@ export function buildBIQuery(config: BIConfig): BIQueryBuildResult | null {
}
: undefined
+ if (hasBIAnalysis(config)) {
+ const placeholder = getBIFiltersPlaceholder(config)
+ const where = (previous: boolean): string =>
+ [
+ previous ? placeholder.replace('{filters', '{filters.previous') : placeholder,
+ ...filters.map((filter) => `(${filter})`),
+ ].join(' AND ')
+ query = buildBIAnalysisQuery(config, {
+ rows: rowDimensions.map((dimension) => ({ ...dimension, expression: fieldExpression(dimension.field) })),
+ columns: columnDimensions.map((dimension) => ({
+ ...dimension,
+ expression: fieldExpression(dimension.field),
+ })),
+ measures: configuredValues.length ? configuredValues : [{ alias: 'count', expression: 'count(*)' }],
+ from: escapePropertyAsHogQLIdentifier(config.source.table),
+ where: where(false),
+ orderBy: orderByExpression,
+ resultLimit,
+ ...(comparing
+ ? {
+ previousWhere: where(true),
+ previousDimensions: dimensions.map(({ field }) =>
+ fieldExpression(
+ isDateTimeBIField(field)
+ ? {
+ ...field,
+ expression: getBIComparisonDateExpression(field),
+ }
+ : field
+ )
+ ),
+ }
+ : {}),
+ })
+ seriesSettings ??= {
+ xAxis: xDimension ? { column: xDimension.alias } : undefined,
+ yAxis: configuredValues.length
+ ? configuredValues.map(({ alias }) => ({ column: alias }))
+ : [{ column: 'count' }],
+ }
+ }
+
+ const calculatedFormats = configuredValues
+ .filter(({ value }) => ['percent_of_total', 'percent_change'].includes(value.tableCalculation?.type ?? ''))
+ .map(({ alias }) => ({
+ column: alias,
+ settings: { formatting: { style: 'percent' as const, decimalPlaces: 1 } },
+ }))
+ if (calculatedFormats.length) {
+ seriesSettings = {
+ ...seriesSettings,
+ yAxis: (seriesSettings?.yAxis ?? configuredValues.map(({ alias }) => ({ column: alias }))).map((axis) => ({
+ ...axis,
+ ...calculatedFormats.find((format) => format.column === axis.column),
+ })),
+ }
+ }
+
return {
query,
node: {
@@ -1154,6 +1248,21 @@ export function buildBIQuery(config: BIConfig): BIQueryBuildResult | null {
filters: getBIQueryFilters(config),
},
display: config.chartType,
+ ...(calculatedFormats.length
+ ? {
+ tableSettings: {
+ columns: [
+ ...(isPivotTable
+ ? [pivotRowAxis, pivotColumnAxis]
+ .filter((axis): axis is BIPivotAxis => !!axis)
+ .map((axis) => axis.alias)
+ : dimensions.map((dimension) => dimension.alias)),
+ ...configuredValues.map((value) => value.alias),
+ ...(comparing ? ['bi_comparison'] : []),
+ ].map((column) => calculatedFormats.find((format) => format.column === column) ?? { column }),
+ },
+ }
+ : {}),
...(pivotTableSettings || seriesSettings ? { chartSettings: pivotTableSettings ?? seriesSettings } : {}),
},
}
diff --git a/products/business_intelligence/frontend/biQueryResults.ts b/products/business_intelligence/frontend/biQueryResults.ts
new file mode 100644
index 000000000000..ed65240c6658
--- /dev/null
+++ b/products/business_intelligence/frontend/biQueryResults.ts
@@ -0,0 +1,30 @@
+import { AnyResponseType, NodeKind, VisualizationNode } from '~/queries/schema/schema-general'
+
+import { buildBIQuery } from './biEditorTypes'
+
+export function getBIVisualizationSource(query: VisualizationNode): VisualizationNode['source'] {
+ if (query.kind !== NodeKind.BIVisualizationNode) {
+ return query.source
+ }
+ const probe = buildBIQuery(query.config, true)
+ return probe ? { ...query.source, query: probe.query } : query.source
+}
+
+export function getBIVisualizationResponse(
+ query: VisualizationNode,
+ response: AnyResponseType | null
+): AnyResponseType | null {
+ if (
+ query.kind !== NodeKind.BIVisualizationNode ||
+ !response ||
+ !('results' in response) ||
+ !Array.isArray(response.results)
+ ) {
+ return response
+ }
+ return {
+ ...response,
+ results: response.results.slice(0, query.config.limit),
+ hasMore: response.results.length > query.config.limit || ('hasMore' in response && response.hasMore === true),
+ }
+}
diff --git a/products/business_intelligence/frontend/components/BIMarksCard.tsx b/products/business_intelligence/frontend/components/BIMarksCard.tsx
index 6be7ec61a9c2..06fdbc04a324 100644
--- a/products/business_intelligence/frontend/components/BIMarksCard.tsx
+++ b/products/business_intelligence/frontend/components/BIMarksCard.tsx
@@ -8,6 +8,8 @@ import { biEditorLogic } from 'products/business_intelligence/frontend/biEditorL
import { getChartTypeOptions } from 'products/business_intelligence/frontend/biEditorOptions'
import { BIShelfCard } from 'products/business_intelligence/frontend/components/BIShelfCard'
+import { BIMeasureAnalysis } from '../BIMeasureAnalysis'
+
export function BIMarksCard(): JSX.Element {
const { config } = useValues(biEditorLogic)
const { setChartType } = useActions(biEditorLogic)
@@ -29,6 +31,9 @@ export function BIMarksCard(): JSX.Element {
data-attr="bi-editor-mark-type"
tooltip="Change how measures on Rows are displayed"
/>
+ {config.values.map((_, index) => (
+ <BIMeasureAnalysis key={index} index={index} />
+ ))}
</BIShelfCard>
)
}
diff --git a/products/business_intelligence/frontend/components/BIToolbar.tsx b/products/business_intelligence/frontend/components/BIToolbar.tsx
index a25d2c0c7c5c..e280938c02ef 100644
--- a/products/business_intelligence/frontend/components/BIToolbar.tsx
+++ b/products/business_intelligence/frontend/components/BIToolbar.tsx
@@ -10,6 +10,7 @@ import { BISortDirection } from '~/queries/schema/schema-business-intelligence'
import { biEditorLogic } from 'products/business_intelligence/frontend/biEditorLogic'
import { LIMIT_OPTIONS } from 'products/business_intelligence/frontend/biEditorOptions'
+import { getBIVisualizationSource } from 'products/business_intelligence/frontend/biQueryResults'
import { biSceneLogic } from 'products/business_intelligence/frontend/biSceneLogic'
import { BIShowMe } from 'products/business_intelligence/frontend/components/BIShowMe'
@@ -21,7 +22,11 @@ export function BIToolbar(): JSX.Element {
const { dataNodeKey, lastRunQuery, worksheet } = useValues(scene)
const { runQuery, cancelQuery } = useActions(scene)
const { responseLoading } = useValues(
- dataNodeLogic({ key: dataNodeKey, query: (lastRunQuery ?? worksheet).source, autoLoad: !!lastRunQuery })
+ dataNodeLogic({
+ key: dataNodeKey,
+ query: getBIVisualizationSource(lastRunQuery ?? worksheet),
+ autoLoad: !!lastRunQuery,
+ })
)
const { autoUpdate, config, generatedQuery, showMeOpen, sortOptions } = useValues(biEditorLogic)
const { resetConfig, setAutoUpdate, setLimit, setShowMeOpen, setSort, swapRowsAndColumns } =
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index bd9492ed3cb4..5077e0b0b0b6 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -9451,6 +9451,21 @@ export interface BISortApi {
key: string
}
+export interface BITopNApi {
+ /** @minimum 1 */
+ count: number
+ fieldId: string
+ includeOther: boolean
+ /** @minimum 0 */
+ measureIndex: number
+}
+
+export interface BITotalsApi {
+ columns?: boolean | null
+ rows?: boolean | null
+ subtotals?: boolean | null
+}
+
export type BIAggregationApi = (typeof BIAggregationApi)[keyof typeof BIAggregationApi]
export const BIAggregationApi = {
@@ -9463,11 +9478,31 @@ export const BIAggregationApi = {
Custom: 'custom',
} as const
+export type BITableCalculationTypeApi = (typeof BITableCalculationTypeApi)[keyof typeof BITableCalculationTypeApi]
+
+export const BITableCalculationTypeApi = {
+ PercentOfTotal: 'percent_of_total',
+ RunningTotal: 'running_total',
+ Difference: 'difference',
+ PercentChange: 'percent_change',
+ MovingAverage: 'moving_average',
+ Rank: 'rank',
+} as const
+
+export interface BITableCalculationApi {
+ /** Dimension ID to traverse. Unset chooses the date dimension; 'table' traverses all dimensions. */
+ computeUsing?: string | null
+ type: BITableCalculationTypeApi
+ /** Number of points, including the current point, in a trailing moving average. */
+ window?: number | null
+}
+
export interface BIValueApi {
aggregation: BIAggregationApi
customExpression?: string | null
field: BIFieldApi
label?: string | null
+ tableCalculation?: BITableCalculationApi | null
}
export interface BIConfigApi {
@@ -9483,6 +9518,8 @@ export interface BIConfigApi {
/** null sorts automatically: newest date or highest value first, so top rows survive the LIMIT. */
sort?: BISortApi | null
source?: BIDataSourceApi | null
+ topN?: BITopNApi | null
+ totals?: BITotalsApi | null
values: BIValueApi[]
}
diff --git a/products/data_warehouse/backend/test/__snapshots__/test_hogql_fixer_ai.ambr b/products/data_warehouse/backend/test/__snapshots__/test_hogql_fixer_ai.ambr
index 27b12086b71c..b6a6b3610018 100644
--- a/products/data_warehouse/backend/test/__snapshots__/test_hogql_fixer_ai.ambr
+++ b/products/data_warehouse/backend/test/__snapshots__/test_hogql_fixer_ai.ambr
@@ -64,7 +64,7 @@
HogQL defines what functions are available with most (but not all) having a 1:1 mapping to ClickHouse functions.
These are the non-aggregated HogQL functions:
```
- ['plus', 'minus', 'multiply', 'divide', 'intDiv', 'intDivOrZero', 'modulo', 'moduloOrZero', 'positiveModulo', 'negate', 'abs', 'gcd', 'lcm', 'max2', 'min2', 'multiplyDecimal', 'divideDecimal', 'empty', 'notEmpty', 'length', 'reverse', 'array', 'range', 'arrayConcat', 'arrayElement', 'has', 'hasAll', 'hasAny', 'hasSubstr', 'indexOf', 'arrayCount', 'countEqual', 'arrayEnumerate', 'arrayEnumerateUniq', 'arrayPopBack', 'arrayPopFront', 'arrayPushBack', 'arrayPushFront', 'arrayResize', 'arraySlice', 'arraySort', 'arrayReverseSort', 'arrayUniq', 'arrayJoin', 'arrayDifference', 'arrayDistinct', 'arrayEnumerateDense', 'arrayIntersect', 'arrayReduce', 'arrayReverse', 'arrayFilter', 'arrayFlatten', 'arrayCompact', 'arrayZip', 'arrayAUC', 'arrayMap', 'arrayFill', 'arrayFold', 'arrayWithConstant', 'arraySplit', 'arrayReverseFill', 'arrayReverseSplit', 'arrayRotateLeft', 'arrayRotateRight', 'arrayExists', 'arrayAll', 'arrayFirst', 'arrayLast', 'arrayFirstIndex', 'arrayLastIndex', 'arrayMin', 'arrayMax', 'arraySum', 'arrayAvg', 'arrayCumSum', 'arrayCumSumNonNegative', 'arrayProduct', 'arrayStringConcat', 'generateSeries', 'hex', 'unhex', 'reinterpretAsUInt8', 'reinterpretAsUInt16', 'reinterpretAsUInt32', 'reinterpretAsUInt64', 'reinterpretAsUInt128', 'reinterpretAsUInt256', 'reinterpretAsInt8', 'reinterpretAsInt16', 'reinterpretAsInt32', 'reinterpretAsInt64', 'reinterpretAsInt128', 'reinterpretAsInt256', 'reinterpretAsFloat32', 'reinterpretAsFloat64', 'reinterpretAsUUID', 'accurateCast', 'accurateCastOrNull', 'toInt', 'toIntOrZero', 'toIntOrDefault', '_toInt8', '_toInt16', '_toInt32', '_toInt64', '_toUInt8', '_toUInt64', '_toUInt128', 'toFloat', 'toFloatOrNull', 'toFloat64OrNull', 'toFloatOrZero', 'toFloatOrDefault', 'toDecimal', '_toDate', 'toUUID', 'toUUIDOrDefault', 'toString', 'toNullableString', 'toBool', 'toJSONString', 'parseDateTime', 'parseDateTimeBestEffort', 'dynamicType', 'toTypeName', 'defaultValueOfTypeName', 'cityHash64', 'MD5', 'UUIDv7ToDateTime', 'toDate', 'to_date', 'toDateTime', 'toDateTime64', 'toDateTimeUS', 'isnull', 'isNotNull', 'coalesce', 'ifnull', 'nullif', 'assumeNotNull', 'toNullable', 'timeZoneOf', 'timeZoneOffset', 'toYear', 'toQuarter', 'toMonth', 'toDayOfYear', 'toDayOfMonth', 'toDayOfWeek', 'toHour', 'toMinute', 'toSecond', 'toUnixTimestamp', 'toUnixTimestamp64Milli', 'fromUnixTimestamp64Milli', 'toStartOfInterval', 'toStartOfYear', 'toStartOfISOYear', 'toStartOfQuarter', 'toStartOfMonth', 'toLastDayOfMonth', 'toMonday', 'toStartOfWeek', 'toStartOfDay', 'toLastDayOfWeek', 'toStartOfHour', 'toStartOfMinute', 'toStartOfSecond', 'toStartOfFiveMinutes', 'toStartOfTenMinutes', 'toStartOfFifteenMinutes', 'toTime', 'toISOYear', 'toISOWeek', 'toWeek', 'toYearWeek', 'age', 'dateAdd', 'dateSub', 'date_bin', 'date_add', 'date_subtract', 'date_diff', 'dateDiff', 'timeStampAdd', 'timeStampSub', 'nowInBlock', 'rowNumberInBlock', 'rowNumberInAllBlocks', 'timeSlot', 'toYYYYMM', 'toYYYYMMDD', 'toYYYYMMDDhhmmss', 'addYears', 'addMonths', 'addWeeks', 'addDays', 'addHours', 'addMinutes', 'addSeconds', 'addQuarters', 'subtractYears', 'subtractMonths', 'subtractWeeks', 'subtractDays', 'subtractHours', 'subtractMinutes', 'subtractSeconds', 'subtractQuarters', 'timeSlots', 'formatDateTime', 'dateName', 'monthName', 'fromUnixTimestamp', 'toModifiedJulianDay', 'fromModifiedJulianDay', 'toIntervalSecond', 'toIntervalMinute', 'toIntervalHour', 'toIntervalDay', 'toIntervalWeek', 'toIntervalMonth', 'toIntervalQuarter', 'toIntervalYear', 'now', 'yesterday', 'current_timestamp', 'today', 'current_date', 'date_part', 'date_trunc', 'dateTrunc', 'to_timestamp', 'to_char', 'make_timestamp', 'make_date', 'make_interval', 'make_timestamptz', 'timezone', 'toTimeZone', 'greatCircleDistance', 'geoDistance', 'greatCircleAngle', 'pointInEllipses', 'pointInPolygon', 'geohashEncode', 'geohashDecode', 'geohashesInBox', 'h3IsValid', 'h3GetResolution', 'h3GetBaseCell', 'h3EdgeAngle', 'h3EdgeLengthM', 'h3EdgeLengthKm', 'geoToH3', 'h3ToGeo', 'h3ToGeoBoundary', 'h3kRing', 'h3HexAreaM2', 'h3HexAreaKm2', 'h3IndexesAreNeighbors', 'h3ToChildren', 'h3ToParent', 'h3ToString', 'stringToH3', 'h3IsResClassIII', 'h3IsPentagon', 'h3GetFaces', 'h3CellAreaM2', 'h3CellAreaRads2', 'h3ToCenterChild', 'h3ExactEdgeLengthM', 'h3ExactEdgeLengthKm', 'h3ExactEdgeLengthRads', 'h3NumHexagons', 'h3PointDistM', 'h3PointDistKm', 'h3PointDistRads', 'h3GetRes0Indexes', 'h3GetPentagonIndexes', 'h3Line', 'h3Distance', 'h3HexRing', 'h3GetUnidirectionalEdge', 'h3UnidirectionalEdgeIsValid', 'h3GetOriginIndexFromUnidirectionalEdge', 'h3GetDestinationIndexFromUnidirectionalEdge', 'h3GetIndexesFromUnidirectionalEdge', 'h3GetUnidirectionalEdgesFromHexagon', 'h3GetUnidirectionalEdgeBoundary', 'isValidJSON', 'JSONHas', 'JSONLength', 'JSONArrayLength', 'JSONType', 'JSONExtract', 'JSONExtractUInt', 'JSONExtractInt', 'JSONExtractFloat', 'JSONExtractBool', 'JSONExtractString', 'JSONExtractKeys', 'JSONExtractRaw', 'JSONExtractArrayRaw', 'JSONExtractKeysAndValues', 'JSONExtractKeysAndValuesRaw', 'JSON_VALUE', 'e', 'pi', 'exp', 'log', 'ln', 'exp2', 'log2', 'exp10', 'log10', 'sqrt', 'cbrt', 'erf', 'erfc', 'lgamma', 'tgamma', 'sin', 'cos', 'tan', 'asin', 'acos', 'atan', 'pow', 'power', 'intExp2', 'intExp10', 'cosh', 'acosh', 'sinh', 'asinh', 'atanh', 'atan2', 'hypot', 'log1p', 'sign', 'degrees', 'radians', 'factorial', 'width_bucket', 'floor', 'ceil', 'trunc', 'round', 'roundBankers', 'roundToExp2', 'roundDuration', 'roundAge', 'roundDown', 'rand', 'left', 'right', 'lengthUTF8', 'leftPad', 'rightPad', 'leftPadUTF8', 'rightPadUTF8', 'lower', 'upper', 'lowerUTF8', 'upperUTF8', 'isValidUTF8', 'toValidUTF8', 'format', 'reverseUTF8', 'concat', 'substring', 'substringUTF8', 'appendTrailingCharIfAbsent', 'convertCharset', 'base58Encode', 'base58Decode', 'tryBase58Decode', 'base64Encode', 'base64Decode', 'tryBase64Decode', 'endsWith', 'startsWith', 'encodeXMLComponent', 'decodeXMLComponent', 'extractTextFromHTML', 'ascii', 'concatWithSeparator', 'position', 'positionCaseInsensitive', 'positionUTF8', 'positionCaseInsensitiveUTF8', 'multiSearchAllPositions', 'multiSearchAllPositionsUTF8', 'multiSearchFirstPosition', 'multiSearchFirstIndex', 'multiSearchAny', 'multiSearchAllPositionsCaseInsensitive', 'multiSearchAllPositionsCaseInsensitiveUTF8', 'multiSearchAnyUTF8', 'multiSearchAnyCaseInsensitive', 'multiSearchAnyCaseInsensitiveUTF8', 'multiSearchFirstIndexUTF8', 'multiSearchFirstIndexCaseInsensitive', 'multiSearchFirstIndexCaseInsensitiveUTF8', 'multiSearchFirstPositionUTF8', 'multiSearchFirstPositionCaseInsensitive', 'multiSearchFirstPositionCaseInsensitiveUTF8', 'match', 'multiMatchAny', 'multiMatchAnyIndex', 'multiMatchAllIndices', 'multiFuzzyMatchAny', 'multiFuzzyMatchAnyIndex', 'multiFuzzyMatchAllIndices', 'extract', 'extractAll', 'extractAllGroupsHorizontal', 'extractAllGroupsVertical', 'extractGroups', 'like', 'ilike', 'notLike', 'notILike', 'locate', 'ngramDistance', 'ngramDistanceCaseInsensitive', 'ngramDistanceUTF8', 'ngramDistanceCaseInsensitiveUTF8', 'ngramSearch', 'ngramSearchCaseInsensitive', 'ngramSearchUTF8', 'ngramSearchCaseInsensitiveUTF8', 'countSubstrings', 'countSubstringsCaseInsensitive', 'countSubstringsCaseInsensitiveUTF8', 'countMatches', 'countMatchesCaseInsensitive', 'hasSubsequence', 'hasSubsequenceCaseInsensitive', 'hasSubsequenceUTF8', 'hasSubsequenceCaseInsensitiveUTF8', 'hasToken', 'hasTokenCaseInsensitive', 'hasTokenOrNull', 'hasTokenCaseInsensitiveOrNull', 'hasAllTokens', 'hasAnyTokens', 'regexpExtract', 'replace', 'replaceAll', 'replaceOne', 'replaceRegexpAll', 'replaceRegexpOne', 'regexpQuoteMeta', 'translate', 'translateUTF8', 'splitByChar', 'splitByString', 'splitByRegexp', 'splitByWhitespace', 'splitByNonAlpha', 'alphaTokens', 'extractAllGroups', 'ngrams', 'tokens', 'repeat', 'initcap', 'lpad', 'rpad', 'split_part', 'ltrim', 'trimLeft', 'rtrim', 'trimRight', 'btrim', 'trim', 'equals', 'notEquals', 'less', 'greater', 'lessOrEquals', 'greaterOrEquals', 'in', 'notIn', 'and', 'or', 'xor', 'not', '_caseWithExpression', 'if', 'multiIf', 'throwIf', 'map', 'mapFromArrays', 'mapAdd', 'mapSubtract', 'mapPopulateSeries', 'mapContains', 'mapKeys', 'mapValues', 'mapContainsKeyLike', 'mapExtractKeyLike', 'mapApply', 'mapFilter', 'mapExists', 'mapUpdate', 'bitAnd', 'bitOr', 'bitXor', 'bitNot', 'bitShiftLeft', 'bitShiftRight', 'bitRotateLeft', 'bitRotateRight', 'bitSlice', 'bitTest', 'bitTestAll', 'bitTestAny', 'bitCount', 'bitHammingDistance', 'bitmapBuild', 'bitmapToArray', 'bitmapSubsetInRange', 'bitmapSubsetLimit', 'subBitmap', 'bitmapContains', 'bitmapHasAny', 'bitmapHasAll', 'bitmapCardinality', 'bitmapMin', 'bitmapMax', 'bitmapTransform', 'bitmapAnd', 'bitmapOr', 'bitmapXor', 'bitmapAndnot', 'bitmapAndCardinality', 'bitmapOrCardinality', 'bitmapXorCardinality', 'bitmapAndnotCardinality', 'protocol', 'domain', 'domainWithoutWWW', 'topLevelDomain', 'firstSignificantSubdomain', 'cutToFirstSignificantSubdomain', 'cutToFirstSignificantSubdomainWithWWW', 'port', 'path', 'pathFull', 'queryString', 'fragment', 'queryStringAndFragment', 'extractURLParameter', 'extractURLParameters', 'extractURLParameterNames', 'URLHierarchy', 'URLPathHierarchy', 'encodeURLComponent', 'decodeURLComponent', 'encodeURLFormComponent', 'decodeURLFormComponent', 'netloc', 'cutWWW', 'cutQueryString', 'cutFragment', 'cutQueryStringAndFragment', 'cutURLParameter', 'IPv4NumToString', 'IPv4StringToNum', 'IPv4StringToNumOrDefault', 'IPv4StringToNumOrNull', 'IPv6NumToString', 'IPv6StringToNum', 'IPv6StringToNumOrDefault', 'IPv6StringToNumOrNull', 'IPv4ToIPv6', 'toIPv4', 'toIPv4OrDefault', 'toIPv4OrNull', 'toIPv4OrZero', 'toIPv6', 'toIPv6OrDefault', 'toIPv6OrNull', 'toIPv6OrZero', 'isIPv4String', 'isIPv6String', 'isIPAddressInRange', 'IPv4CIDRToRange', 'IPv6CIDRToRange', 'cutIPv6', 'tuple', 'tupleElement', 'untuple', 'tupleHammingDistance', 'tupleToNameValuePairs', 'tuplePlus', 'tupleMinus', 'tupleMultiply', 'tupleDivide', 'tupleNegate', 'tupleMultiplyByNumber', 'tupleDivideByNumber', 'dotProduct', 'isFinite', 'isInfinite', 'ifNotFinite', 'isNaN', 'bar', 'transform', 'formatReadableDecimalSize', 'formatReadableSize', 'formatReadableQuantity', 'formatReadableTimeDelta', 'least', 'greatest', 'indexHint', 'extractIPv4Substrings', 'tumble', 'hop', 'tumbleStart', 'tumbleEnd', 'hopStart', 'hopEnd', 'L1Norm', 'L2Norm', 'LinfNorm', 'LpNorm', 'L1Distance', 'L2Distance', 'LinfDistance', 'LpDistance', 'L1Normalize', 'L2Normalize', 'LinfNormalize', 'LpNormalize', 'cosineDistance', 'rank', 'dense_rank', 'row_number', 'first_value', 'last_value', 'nth_value', 'lagInFrame', 'leadInFrame', 'lag', 'lead', 'languageCodeToName', '_finalizeAggregation', 'aggregate_funnel', 'aggregate_funnel_array', 'aggregate_funnel_cohort', 'aggregate_funnel_trends', 'aggregate_funnel_array_trends', 'aggregate_funnel_cohort_trends', 'aggregate_funnel_json', 'aggregate_funnel_array_json', 'aggregate_funnel_cohort_json', 'aggregate_funnel_trends_json', 'aggregate_funnel_array_trends_json', 'aggregate_funnel_cohort_trends_json', 'aggregate_funnel_test', 'aggregate_funnel_array_trends_test']
+ ['plus', 'minus', 'multiply', 'divide', 'intDiv', 'intDivOrZero', 'modulo', 'moduloOrZero', 'positiveModulo', 'negate', 'abs', 'gcd', 'lcm', 'max2', 'min2', 'multiplyDecimal', 'divideDecimal', 'empty', 'notEmpty', 'length', 'reverse', 'array', 'range', 'arrayConcat', 'arrayElement', 'has', 'hasAll', 'hasAny', 'hasSubstr', 'indexOf', 'arrayCount', 'countEqual', 'arrayEnumerate', 'arrayEnumerateUniq', 'arrayPopBack', 'arrayPopFront', 'arrayPushBack', 'arrayPushFront', 'arrayResize', 'arraySlice', 'arraySort', 'arrayReverseSort', 'arrayUniq', 'arrayJoin', 'arrayDifference', 'arrayDistinct', 'arrayEnumerateDense', 'arrayIntersect', 'arrayReduce', 'arrayReverse', 'arrayFilter', 'arrayFlatten', 'arrayCompact', 'arrayZip', 'arrayAUC', 'arrayMap', 'arrayFill', 'arrayFold', 'arrayWithConstant', 'arraySplit', 'arrayReverseFill', 'arrayReverseSplit', 'arrayRotateLeft', 'arrayRotateRight', 'arrayExists', 'arrayAll', 'arrayFirst', 'arrayLast', 'arrayFirstIndex', 'arrayLastIndex', 'arrayMin', 'arrayMax', 'arraySum', 'arrayAvg', 'arrayCumSum', 'arrayCumSumNonNegative', 'arrayProduct', 'arrayStringConcat', 'generateSeries', 'hex', 'unhex', 'reinterpretAsUInt8', 'reinterpretAsUInt16', 'reinterpretAsUInt32', 'reinterpretAsUInt64', 'reinterpretAsUInt128', 'reinterpretAsUInt256', 'reinterpretAsInt8', 'reinterpretAsInt16', 'reinterpretAsInt32', 'reinterpretAsInt64', 'reinterpretAsInt128', 'reinterpretAsInt256', 'reinterpretAsFloat32', 'reinterpretAsFloat64', 'reinterpretAsUUID', 'accurateCast', 'accurateCastOrNull', 'toInt', 'toIntOrZero', 'toIntOrDefault', '_toInt8', '_toInt16', '_toInt32', '_toInt64', '_toUInt8', '_toUInt64', '_toUInt128', 'toFloat', 'toFloatOrNull', 'toFloat64OrNull', 'toFloatOrZero', 'toFloatOrDefault', 'toDecimal', '_toDate', 'toUUID', 'toUUIDOrDefault', 'toString', 'toNullableString', 'toBool', 'toJSONString', 'parseDateTime', 'parseDateTimeBestEffort', 'dynamicType', 'toTypeName', 'defaultValueOfTypeName', 'cityHash64', 'MD5', 'UUIDv7ToDateTime', 'toDate', 'to_date', 'toDateTime', 'toDateTime64', 'toDateTimeUS', 'isnull', 'isNotNull', 'coalesce', 'ifnull', 'nullif', 'assumeNotNull', 'toNullable', 'timeZoneOf', 'timeZoneOffset', 'toYear', 'toQuarter', 'toMonth', 'toDayOfYear', 'toDayOfMonth', 'toDayOfWeek', 'toHour', 'toMinute', 'toSecond', 'toUnixTimestamp', 'toUnixTimestamp64Milli', 'fromUnixTimestamp64Milli', 'toStartOfInterval', 'toStartOfYear', 'toStartOfISOYear', 'toStartOfQuarter', 'toStartOfMonth', 'toLastDayOfMonth', 'toMonday', 'toStartOfWeek', 'toStartOfDay', 'toLastDayOfWeek', 'toStartOfHour', 'toStartOfMinute', 'toStartOfSecond', 'toStartOfFiveMinutes', 'toStartOfTenMinutes', 'toStartOfFifteenMinutes', 'toTime', 'toISOYear', 'toISOWeek', 'toWeek', 'toYearWeek', 'age', 'dateAdd', 'dateSub', 'date_bin', 'date_add', 'date_subtract', 'date_diff', 'dateDiff', 'timeStampAdd', 'timeStampSub', 'nowInBlock', 'rowNumberInBlock', 'rowNumberInAllBlocks', 'timeSlot', 'toYYYYMM', 'toYYYYMMDD', 'toYYYYMMDDhhmmss', 'addYears', 'addMonths', 'addWeeks', 'addDays', 'addHours', 'addMinutes', 'addSeconds', 'addQuarters', 'subtractYears', 'subtractMonths', 'subtractWeeks', 'subtractDays', 'subtractHours', 'subtractMinutes', 'subtractSeconds', 'subtractQuarters', 'timeSlots', 'formatDateTime', 'dateName', 'monthName', 'fromUnixTimestamp', 'toModifiedJulianDay', 'fromModifiedJulianDay', 'toIntervalSecond', 'toIntervalMinute', 'toIntervalHour', 'toIntervalDay', 'toIntervalWeek', 'toIntervalMonth', 'toIntervalQuarter', 'toIntervalYear', 'now', 'yesterday', 'current_timestamp', 'today', 'current_date', 'date_part', 'date_trunc', 'dateTrunc', 'to_timestamp', 'to_char', 'make_timestamp', 'make_date', 'make_interval', 'make_timestamptz', 'timezone', 'toTimeZone', 'greatCircleDistance', 'geoDistance', 'greatCircleAngle', 'pointInEllipses', 'pointInPolygon', 'geohashEncode', 'geohashDecode', 'geohashesInBox', 'h3IsValid', 'h3GetResolution', 'h3GetBaseCell', 'h3EdgeAngle', 'h3EdgeLengthM', 'h3EdgeLengthKm', 'geoToH3', 'h3ToGeo', 'h3ToGeoBoundary', 'h3kRing', 'h3HexAreaM2', 'h3HexAreaKm2', 'h3IndexesAreNeighbors', 'h3ToChildren', 'h3ToParent', 'h3ToString', 'stringToH3', 'h3IsResClassIII', 'h3IsPentagon', 'h3GetFaces', 'h3CellAreaM2', 'h3CellAreaRads2', 'h3ToCenterChild', 'h3ExactEdgeLengthM', 'h3ExactEdgeLengthKm', 'h3ExactEdgeLengthRads', 'h3NumHexagons', 'h3PointDistM', 'h3PointDistKm', 'h3PointDistRads', 'h3GetRes0Indexes', 'h3GetPentagonIndexes', 'h3Line', 'h3Distance', 'h3HexRing', 'h3GetUnidirectionalEdge', 'h3UnidirectionalEdgeIsValid', 'h3GetOriginIndexFromUnidirectionalEdge', 'h3GetDestinationIndexFromUnidirectionalEdge', 'h3GetIndexesFromUnidirectionalEdge', 'h3GetUnidirectionalEdgesFromHexagon', 'h3GetUnidirectionalEdgeBoundary', 'isValidJSON', 'JSONHas', 'JSONLength', 'JSONArrayLength', 'JSONType', 'JSONExtract', 'JSONExtractUInt', 'JSONExtractInt', 'JSONExtractFloat', 'JSONExtractBool', 'JSONExtractString', 'JSONExtractKeys', 'JSONExtractRaw', 'JSONExtractArrayRaw', 'JSONExtractKeysAndValues', 'JSONExtractKeysAndValuesRaw', 'JSON_VALUE', 'e', 'pi', 'exp', 'log', 'ln', 'exp2', 'log2', 'exp10', 'log10', 'sqrt', 'cbrt', 'erf', 'erfc', 'lgamma', 'tgamma', 'sin', 'cos', 'tan', 'asin', 'acos', 'atan', 'pow', 'power', 'intExp2', 'intExp10', 'cosh', 'acosh', 'sinh', 'asinh', 'atanh', 'atan2', 'hypot', 'log1p', 'sign', 'degrees', 'radians', 'factorial', 'width_bucket', 'floor', 'ceil', 'trunc', 'round', 'roundBankers', 'roundToExp2', 'roundDuration', 'roundAge', 'roundDown', 'rand', 'left', 'right', 'lengthUTF8', 'leftPad', 'rightPad', 'leftPadUTF8', 'rightPadUTF8', 'lower', 'upper', 'lowerUTF8', 'upperUTF8', 'isValidUTF8', 'toValidUTF8', 'format', 'reverseUTF8', 'concat', 'substring', 'substringUTF8', 'appendTrailingCharIfAbsent', 'convertCharset', 'base58Encode', 'base58Decode', 'tryBase58Decode', 'base64Encode', 'base64Decode', 'tryBase64Decode', 'endsWith', 'startsWith', 'encodeXMLComponent', 'decodeXMLComponent', 'extractTextFromHTML', 'ascii', 'concatWithSeparator', 'position', 'positionCaseInsensitive', 'positionUTF8', 'positionCaseInsensitiveUTF8', 'multiSearchAllPositions', 'multiSearchAllPositionsUTF8', 'multiSearchFirstPosition', 'multiSearchFirstIndex', 'multiSearchAny', 'multiSearchAllPositionsCaseInsensitive', 'multiSearchAllPositionsCaseInsensitiveUTF8', 'multiSearchAnyUTF8', 'multiSearchAnyCaseInsensitive', 'multiSearchAnyCaseInsensitiveUTF8', 'multiSearchFirstIndexUTF8', 'multiSearchFirstIndexCaseInsensitive', 'multiSearchFirstIndexCaseInsensitiveUTF8', 'multiSearchFirstPositionUTF8', 'multiSearchFirstPositionCaseInsensitive', 'multiSearchFirstPositionCaseInsensitiveUTF8', 'match', 'multiMatchAny', 'multiMatchAnyIndex', 'multiMatchAllIndices', 'multiFuzzyMatchAny', 'multiFuzzyMatchAnyIndex', 'multiFuzzyMatchAllIndices', 'extract', 'extractAll', 'extractAllGroupsHorizontal', 'extractAllGroupsVertical', 'extractGroups', 'like', 'ilike', 'notLike', 'notILike', 'locate', 'ngramDistance', 'ngramDistanceCaseInsensitive', 'ngramDistanceUTF8', 'ngramDistanceCaseInsensitiveUTF8', 'ngramSearch', 'ngramSearchCaseInsensitive', 'ngramSearchUTF8', 'ngramSearchCaseInsensitiveUTF8', 'countSubstrings', 'countSubstringsCaseInsensitive', 'countSubstringsCaseInsensitiveUTF8', 'countMatches', 'countMatchesCaseInsensitive', 'hasSubsequence', 'hasSubsequenceCaseInsensitive', 'hasSubsequenceUTF8', 'hasSubsequenceCaseInsensitiveUTF8', 'hasToken', 'hasTokenCaseInsensitive', 'hasTokenOrNull', 'hasTokenCaseInsensitiveOrNull', 'hasAllTokens', 'hasAnyTokens', 'regexpExtract', 'replace', 'replaceAll', 'replaceOne', 'replaceRegexpAll', 'replaceRegexpOne', 'regexpQuoteMeta', 'translate', 'translateUTF8', 'splitByChar', 'splitByString', 'splitByRegexp', 'splitByWhitespace', 'splitByNonAlpha', 'alphaTokens', 'extractAllGroups', 'ngrams', 'tokens', 'repeat', 'initcap', 'lpad', 'rpad', 'split_part', 'ltrim', 'trimLeft', 'rtrim', 'trimRight', 'btrim', 'trim', 'equals', 'notEquals', 'less', 'greater', 'lessOrEquals', 'greaterOrEquals', 'in', 'notIn', 'and', 'or', 'xor', 'not', '_caseWithExpression', 'if', 'multiIf', 'throwIf', 'map', 'mapFromArrays', 'mapAdd', 'mapSubtract', 'mapPopulateSeries', 'mapContains', 'mapKeys', 'mapValues', 'mapContainsKeyLike', 'mapExtractKeyLike', 'mapApply', 'mapFilter', 'mapExists', 'mapUpdate', 'bitAnd', 'bitOr', 'bitXor', 'bitNot', 'bitShiftLeft', 'bitShiftRight', 'bitRotateLeft', 'bitRotateRight', 'bitSlice', 'bitTest', 'bitTestAll', 'bitTestAny', 'bitCount', 'bitHammingDistance', 'bitmapBuild', 'bitmapToArray', 'bitmapSubsetInRange', 'bitmapSubsetLimit', 'subBitmap', 'bitmapContains', 'bitmapHasAny', 'bitmapHasAll', 'bitmapCardinality', 'bitmapMin', 'bitmapMax', 'bitmapTransform', 'bitmapAnd', 'bitmapOr', 'bitmapXor', 'bitmapAndnot', 'bitmapAndCardinality', 'bitmapOrCardinality', 'bitmapXorCardinality', 'bitmapAndnotCardinality', 'protocol', 'domain', 'domainWithoutWWW', 'topLevelDomain', 'firstSignificantSubdomain', 'cutToFirstSignificantSubdomain', 'cutToFirstSignificantSubdomainWithWWW', 'port', 'path', 'pathFull', 'queryString', 'fragment', 'queryStringAndFragment', 'extractURLParameter', 'extractURLParameters', 'extractURLParameterNames', 'URLHierarchy', 'URLPathHierarchy', 'encodeURLComponent', 'decodeURLComponent', 'encodeURLFormComponent', 'decodeURLFormComponent', 'netloc', 'cutWWW', 'cutQueryString', 'cutFragment', 'cutQueryStringAndFragment', 'cutURLParameter', 'IPv4NumToString', 'IPv4StringToNum', 'IPv4StringToNumOrDefault', 'IPv4StringToNumOrNull', 'IPv6NumToString', 'IPv6StringToNum', 'IPv6StringToNumOrDefault', 'IPv6StringToNumOrNull', 'IPv4ToIPv6', 'toIPv4', 'toIPv4OrDefault', 'toIPv4OrNull', 'toIPv4OrZero', 'toIPv6', 'toIPv6OrDefault', 'toIPv6OrNull', 'toIPv6OrZero', 'isIPv4String', 'isIPv6String', 'isIPAddressInRange', 'IPv4CIDRToRange', 'IPv6CIDRToRange', 'cutIPv6', 'tuple', 'tupleElement', 'untuple', 'tupleHammingDistance', 'tupleToNameValuePairs', 'tuplePlus', 'tupleMinus', 'tupleMultiply', 'tupleDivide', 'tupleNegate', 'tupleMultiplyByNumber', 'tupleDivideByNumber', 'dotProduct', 'isFinite', 'isInfinite', 'ifNotFinite', 'isNaN', 'bar', 'transform', 'formatReadableDecimalSize', 'formatReadableSize', 'formatReadableQuantity', 'formatReadableTimeDelta', 'least', 'greatest', 'indexHint', 'extractIPv4Substrings', 'tumble', 'hop', 'tumbleStart', 'tumbleEnd', 'hopStart', 'hopEnd', 'L1Norm', 'L2Norm', 'LinfNorm', 'LpNorm', 'L1Distance', 'L2Distance', 'LinfDistance', 'LpDistance', 'L1Normalize', 'L2Normalize', 'LinfNormalize', 'LpNormalize', 'cosineDistance', 'grouping', 'rank', 'dense_rank', 'row_number', 'first_value', 'last_value', 'nth_value', 'lagInFrame', 'leadInFrame', 'lag', 'lead', 'languageCodeToName', '_finalizeAggregation', 'aggregate_funnel', 'aggregate_funnel_array', 'aggregate_funnel_cohort', 'aggregate_funnel_trends', 'aggregate_funnel_array_trends', 'aggregate_funnel_cohort_trends', 'aggregate_funnel_json', 'aggregate_funnel_array_json', 'aggregate_funnel_cohort_json', 'aggregate_funnel_trends_json', 'aggregate_funnel_array_trends_json', 'aggregate_funnel_cohort_trends_json', 'aggregate_funnel_test', 'aggregate_funnel_array_trends_test']
```
These are the aggregated HogQL functions:
diff --git a/products/data_warehouse/frontend/sql_editor/aiChartRecommendationLogic.ts b/products/data_warehouse/frontend/sql_editor/aiChartRecommendationLogic.ts
index 289bb448e08d..7c554b464997 100644
--- a/products/data_warehouse/frontend/sql_editor/aiChartRecommendationLogic.ts
+++ b/products/data_warehouse/frontend/sql_editor/aiChartRecommendationLogic.ts
@@ -52,6 +52,7 @@ import type {
TraceSpansQueryResponse,
TraceSpansTreeQueryResponse,
} from '../../../../frontend/src/queries/schema/schema-general'
+import type { AnyResponseType } from '../../../../frontend/src/queries/schema/schema-general'
import type { PreflightStatus } from '../../../../frontend/src/types'
import { ChartRecommendation, buildChartDecision, readChartDecision } from './chartRecommendation'
@@ -148,22 +149,7 @@ export interface aiChartRecommendationLogicValues {
dataProcessingAccepted: boolean // aiConsentLogic
columns: Column[] // dataVisualizationLogic
query: VisualizationNode // dataVisualizationLogic
- response:
- | ErrorTrackingQueryResponse
- | HogQLAutocompleteResponse
- | HogQLMetadataResponse
- | HogQLQueryResponse<any[]>
- | HogQueryResponse
- | LogAttributesQueryResponse
- | LogValuesQueryResponse
- | MetricsQueryResponse
- | Record<string, any>
- | SessionsQueryResponse
- | TraceSpansAggregationQueryResponse
- | TraceSpansAttributeBreakdownQueryResponse
- | TraceSpansQueryResponse
- | TraceSpansTreeQueryResponse
- | null // dataVisualizationLogic
+ response: AnyResponseType | null // dataVisualizationLogic
responseLoading: boolean // dataVisualizationLogic
featureFlags: FeatureFlagsSet // featureFlagLogic
activeTab: OutputTab // outputPaneLogic
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index 49f566ccd46b..f9895091de1f 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -8378,6 +8378,21 @@ export interface BISortApi {
key: string
}
+export interface BITopNApi {
+ /** @minimum 1 */
+ count: number
+ fieldId: string
+ includeOther: boolean
+ /** @minimum 0 */
+ measureIndex: number
+}
+
+export interface BITotalsApi {
+ columns?: boolean | null
+ rows?: boolean | null
+ subtotals?: boolean | null
+}
+
export type BIAggregationApi = (typeof BIAggregationApi)[keyof typeof BIAggregationApi]
export const BIAggregationApi = {
@@ -8390,11 +8405,31 @@ export const BIAggregationApi = {
Custom: 'custom',
} as const
+export type BITableCalculationTypeApi = (typeof BITableCalculationTypeApi)[keyof typeof BITableCalculationTypeApi]
+
+export const BITableCalculationTypeApi = {
+ PercentOfTotal: 'percent_of_total',
+ RunningTotal: 'running_total',
+ Difference: 'difference',
+ PercentChange: 'percent_change',
+ MovingAverage: 'moving_average',
+ Rank: 'rank',
+} as const
+
+export interface BITableCalculationApi {
+ /** Dimension ID to traverse. Unset chooses the date dimension; 'table' traverses all dimensions. */
+ computeUsing?: string | null
+ type: BITableCalculationTypeApi
+ /** Number of points, including the current point, in a trailing moving average. */
+ window?: number | null
+}
+
export interface BIValueApi {
aggregation: BIAggregationApi
customExpression?: string | null
field: BIFieldApi
label?: string | null
+ tableCalculation?: BITableCalculationApi | null
}
export interface BIConfigApi {
@@ -8410,6 +8445,8 @@ export interface BIConfigApi {
/** null sorts automatically: newest date or highest value first, so top rows survive the LIMIT. */
sort?: BISortApi | null
source?: BIDataSourceApi | null
+ topN?: BITopNApi | null
+ totals?: BITotalsApi | null
values: BIValueApi[]
}
diff --git a/services/hogql-language-service/internal/completion/functions.go b/services/hogql-language-service/internal/completion/functions.go
index 8b6bf34f567b..e08cf9d346b9 100644
--- a/services/hogql-language-service/internal/completion/functions.go
+++ b/services/hogql-language-service/internal/completion/functions.go
@@ -29,39 +29,39 @@ e embedText empty encodeURLComponent encodeURLFormComponent encodeXMLComponent e
extractGroups extractIPv4Substrings extractTextFromHTML extractURLParameter extractURLParameterNames extractURLParameters factorial firstSignificantSubdomain first_value floor format formatDateTime formatReadableDecimalSize formatReadableQuantity formatReadableSize formatReadableTimeDelta fragment fromModifiedJulianDay fromUnixTimestamp fromUnixTimestamp64Milli
gcd generateSeries geoDistance geoToH3 geohashDecode geohashEncode geohashesInBox getBotName getBotOperator getBotType getSurveyResponse getTrafficCategory getTrafficType greatCircleAngle greatCircleDistance greater greaterOrEquals greatest groupArray groupArrayIf
groupArrayInsertAt groupArrayInsertAtIf groupArrayMovingAvg groupArrayMovingAvgIf groupArrayMovingSum groupArrayMovingSumIf groupArraySample groupArraySampleIf groupBitAnd groupBitAndIf groupBitOr groupBitOrIf groupBitXor groupBitXorIf groupBitmap groupBitmapAnd groupBitmapAndIf groupBitmapAndState groupBitmapIf groupBitmapOr
-groupBitmapOrIf groupBitmapOrState groupBitmapState groupBitmapXor groupBitmapXorIf groupUniqArray groupUniqArrayArray groupUniqArrayArrayIf groupUniqArrayIf h3CellAreaM2 h3CellAreaRads2 h3Distance h3EdgeAngle h3EdgeLengthKm h3EdgeLengthM h3ExactEdgeLengthKm h3ExactEdgeLengthM h3ExactEdgeLengthRads h3GetBaseCell h3GetDestinationIndexFromUnidirectionalEdge
-h3GetFaces h3GetIndexesFromUnidirectionalEdge h3GetOriginIndexFromUnidirectionalEdge h3GetPentagonIndexes h3GetRes0Indexes h3GetResolution h3GetUnidirectionalEdge h3GetUnidirectionalEdgeBoundary h3GetUnidirectionalEdgesFromHexagon h3HexAreaKm2 h3HexAreaM2 h3HexRing h3IndexesAreNeighbors h3IsPentagon h3IsResClassIII h3IsValid h3Line h3NumHexagons h3PointDistKm h3PointDistM
-h3PointDistRads h3ToCenterChild h3ToChildren h3ToGeo h3ToGeoBoundary h3ToParent h3ToString h3UnidirectionalEdgeIsValid h3kRing has hasAll hasAllTokens hasAny hasAnyTokens hasSubsequence hasSubsequenceCaseInsensitive hasSubsequenceCaseInsensitiveUTF8 hasSubsequenceUTF8 hasSubstr hasToken
-hasTokenCaseInsensitive hasTokenCaseInsensitiveOrNull hasTokenOrNull hex hop hopEnd hopStart hypot if ifNotFinite ifnull ilike in indexHint indexOf initcap intDiv intDivOrZero intExp10 intExp2
-isFinite isIPAddressInRange isIPv4String isIPv6String isInfinite isLikelyBot isNaN isNotNull isValidJSON isValidUTF8 isnull jev json_agg kurtPop kurtPopIf kurtSamp kurtSampIf lag lagInFrame languageCodeToName
-last_value lcm lead leadInFrame least left leftPad leftPadUTF8 length lengthUTF8 less lessOrEquals lgamma like ln locate log log10 log1p log2
-lookupDomainType lookupOrganicMediumType lookupOrganicSourceType lookupPaidMediumType lookupPaidSourceType lower lowerUTF8 lpad ltrim make_date make_interval make_timestamp make_timestamptz map mapAdd mapApply mapContains mapContainsKeyLike mapExists mapExtractKeyLike
-mapFilter mapFromArrays mapKeys mapPopulateSeries mapSubtract mapUpdate mapValues match matchesAction max max2 maxArgMax maxArgMaxIf maxArgMaxOrDefault maxArgMaxOrDefaultIf maxArgMaxOrNull maxArgMaxOrNullIf maxArgMin maxArgMinIf maxArgMinOrDefault
-maxArgMinOrDefaultIf maxArgMinOrNull maxArgMinOrNullIf maxArray maxArrayIf maxArrayOrDefault maxArrayOrDefaultIf maxArrayOrNull maxArrayOrNullIf maxForEach maxForEachIf maxForEachOrDefault maxForEachOrDefaultIf maxForEachOrNull maxForEachOrNullIf maxIf maxIntersections maxIntersectionsIf maxIntersectionsPosition maxIntersectionsPositionIf
-maxMap maxMapIf maxMapOrDefault maxMapOrDefaultIf maxMapOrNull maxMapOrNullIf maxMerge maxMergeIf maxMergeOrDefault maxMergeOrDefaultIf maxMergeOrNull maxMergeOrNullIf maxOrDefault maxOrDefaultIf maxOrNull maxOrNullIf maxState maxStateIf maxStateOrDefault maxStateOrDefaultIf
-maxStateOrNull maxStateOrNullIf md5 median medianArgMax medianArgMaxIf medianArgMaxOrDefault medianArgMaxOrDefaultIf medianArgMaxOrNull medianArgMaxOrNullIf medianArgMin medianArgMinIf medianArgMinOrDefault medianArgMinOrDefaultIf medianArgMinOrNull medianArgMinOrNullIf medianArray medianArrayIf medianArrayOrDefault medianArrayOrDefaultIf
-medianArrayOrNull medianArrayOrNullIf medianBFloat16 medianBFloat16If medianDeterministic medianDeterministicIf medianExact medianExactHigh medianExactHighIf medianExactIf medianExactLow medianExactLowIf medianExactWeighted medianExactWeightedIf medianForEach medianForEachIf medianForEachOrDefault medianForEachOrDefaultIf medianForEachOrNull medianForEachOrNullIf
-medianIf medianMap medianMapIf medianMapOrDefault medianMapOrDefaultIf medianMapOrNull medianMapOrNullIf medianMerge medianMergeIf medianMergeOrDefault medianMergeOrDefaultIf medianMergeOrNull medianMergeOrNullIf medianOrDefault medianOrDefaultIf medianOrNull medianOrNullIf medianState medianStateIf medianStateOrDefault
-medianStateOrDefaultIf medianStateOrNull medianStateOrNullIf medianTDigest medianTDigestIf medianTDigestWeighted medianTDigestWeightedIf medianTiming medianTimingIf medianTimingWeighted medianTimingWeightedIf min min2 minArgMax minArgMaxIf minArgMaxOrDefault minArgMaxOrDefaultIf minArgMaxOrNull minArgMaxOrNullIf minArgMin
-minArgMinIf minArgMinOrDefault minArgMinOrDefaultIf minArgMinOrNull minArgMinOrNullIf minArray minArrayIf minArrayOrDefault minArrayOrDefaultIf minArrayOrNull minArrayOrNullIf minForEach minForEachIf minForEachOrDefault minForEachOrDefaultIf minForEachOrNull minForEachOrNullIf minIf minMap minMapIf
-minMapOrDefault minMapOrDefaultIf minMapOrNull minMapOrNullIf minMerge minMergeIf minMergeOrDefault minMergeOrDefaultIf minMergeOrNull minMergeOrNullIf minOrDefault minOrDefaultIf minOrNull minOrNullIf minState minStateIf minStateOrDefault minStateOrDefaultIf minStateOrNull minStateOrNullIf
-minus modulo moduloOrZero monthName multiFuzzyMatchAllIndices multiFuzzyMatchAny multiFuzzyMatchAnyIndex multiIf multiMatchAllIndices multiMatchAny multiMatchAnyIndex multiSearchAllPositions multiSearchAllPositionsCaseInsensitive multiSearchAllPositionsCaseInsensitiveUTF8 multiSearchAllPositionsUTF8 multiSearchAny multiSearchAnyCaseInsensitive multiSearchAnyCaseInsensitiveUTF8 multiSearchAnyUTF8 multiSearchFirstIndex
-multiSearchFirstIndexCaseInsensitive multiSearchFirstIndexCaseInsensitiveUTF8 multiSearchFirstIndexUTF8 multiSearchFirstPosition multiSearchFirstPositionCaseInsensitive multiSearchFirstPositionCaseInsensitiveUTF8 multiSearchFirstPositionUTF8 multiply multiplyDecimal negate netloc ngramDistance ngramDistanceCaseInsensitive ngramDistanceCaseInsensitiveUTF8 ngramDistanceUTF8 ngramSearch ngramSearchCaseInsensitive ngramSearchCaseInsensitiveUTF8 ngramSearchUTF8 ngrams
-not notEmpty notEquals notILike notIn notLike now nowInBlock nth_value nullif or parseDateTime parseDateTimeBestEffort path pathFull percentile_cont percentile_disc pi plus pointInEllipses
-pointInPolygon port position positionCaseInsensitive positionCaseInsensitiveUTF8 positionUTF8 positiveModulo pow power protocol quantile quantileExact quantileIf quantiles quantilesIf quantilesMerge quantilesMergeIf quantilesState quantilesStateIf queryString
-queryStringAndFragment radians rand range rank recordingButton regexpExtract regexpQuoteMeta reinterpretAsFloat32 reinterpretAsFloat64 reinterpretAsInt128 reinterpretAsInt16 reinterpretAsInt256 reinterpretAsInt32 reinterpretAsInt64 reinterpretAsInt8 reinterpretAsUInt128 reinterpretAsUInt16 reinterpretAsUInt256 reinterpretAsUInt32
-reinterpretAsUInt64 reinterpretAsUInt8 reinterpretAsUUID repeat replace replaceAll replaceOne replaceRegexpAll replaceRegexpOne reverse reverseUTF8 right rightPad rightPadUTF8 round roundAge roundBankers roundDown roundDuration roundToExp2
-rowNumberInAllBlocks rowNumberInBlock row_number rpad rtrim sign simpleLinearRegression simpleLinearRegressionIf sin sinh skewPop skewPopIf skewSamp skewSampIf sortablesemver sparkline splitByChar splitByNonAlpha splitByRegexp splitByString
-splitByWhitespace split_part sqrt startsWith stddevPop stddevPopIf stddevSamp stddevSampIf stringToH3 string_agg subBitmap substring substringUTF8 subtractDays subtractHours subtractMinutes subtractMonths subtractQuarters subtractSeconds subtractWeeks
-subtractYears sum sumArgMax sumArgMaxIf sumArgMaxOrDefault sumArgMaxOrDefaultIf sumArgMaxOrNull sumArgMaxOrNullIf sumArgMin sumArgMinIf sumArgMinOrDefault sumArgMinOrDefaultIf sumArgMinOrNull sumArgMinOrNullIf sumArray sumArrayIf sumArrayOrDefault sumArrayOrDefaultIf sumArrayOrNull sumArrayOrNullIf
-sumForEach sumForEachIf sumForEachMerge sumForEachOrDefault sumForEachOrDefaultIf sumForEachOrNull sumForEachOrNullIf sumForEachState sumIf sumMap sumMapIf sumMapMerge sumMapMergeIf sumMapOrDefault sumMapOrDefaultIf sumMapOrNull sumMapOrNullIf sumMerge sumMergeIf sumMergeOrDefault
-sumMergeOrDefaultIf sumMergeOrNull sumMergeOrNullIf sumOrDefault sumOrDefaultIf sumOrNull sumOrNullIf sumState sumStateIf sumStateOrDefault sumStateOrDefaultIf sumStateOrNull sumStateOrNullIf sumWithOverflow sumWithOverflowIf tan tgamma theilsU theilsUIf throwIf
-timeSlot timeSlots timeStampAdd timeStampSub timeZoneOf timeZoneOffset timezone toBool toDate toDateTime toDateTime64 toDateTimeUS toDayOfMonth toDayOfWeek toDayOfYear toDecimal toFloat toFloat64OrNull toFloatOrDefault toFloatOrNull
-toFloatOrZero toHour toIPv4 toIPv4OrDefault toIPv4OrNull toIPv4OrZero toIPv6 toIPv6OrDefault toIPv6OrNull toIPv6OrZero toISOWeek toISOYear toInt toIntOrDefault toIntOrZero toIntervalDay toIntervalHour toIntervalMinute toIntervalMonth toIntervalQuarter
-toIntervalSecond toIntervalWeek toIntervalYear toJSONString toLastDayOfMonth toLastDayOfWeek toMinute toModifiedJulianDay toMonday toMonth toNullable toNullableString toQuarter toSecond toStartOfDay toStartOfFifteenMinutes toStartOfFiveMinutes toStartOfHour toStartOfISOYear toStartOfInterval
-toStartOfMinute toStartOfMonth toStartOfQuarter toStartOfSecond toStartOfTenMinutes toStartOfWeek toStartOfYear toString toTime toTimeZone toTypeName toUUID toUUIDOrDefault toUnixTimestamp toUnixTimestamp64Milli toValidUTF8 toWeek toYYYYMM toYYYYMMDD toYYYYMMDDhhmmss
-toYear toYearWeek to_char to_date to_timestamp today tokens topK topLevelDomain transform translate translateUTF8 trim trimLeft trimRight trunc tryBase58Decode tryBase64Decode tumble tumbleEnd
-tumbleStart tuple tupleDivide tupleDivideByNumber tupleElement tupleHammingDistance tupleMinus tupleMultiply tupleMultiplyByNumber tupleNegate tuplePlus tupleToNameValuePairs unhex uniq uniqCombined uniqCombined64 uniqExact uniqExactIf uniqExactMerge uniqExactState
-uniqHLL12 uniqHLL12If uniqIf uniqMap uniqMapMerge uniqMapMergeIf uniqMerge uniqMergeIf uniqState uniqStateIf uniqTheta uniqThetaIf uniqUpToMerge uniqueSurveySubmissionsFilter untuple upper upperUTF8 varPop varPopIf varSamp
-varSampIf width_bucket windowFunnel xor yesterday
+groupBitmapOrIf groupBitmapOrState groupBitmapState groupBitmapXor groupBitmapXorIf groupUniqArray groupUniqArrayArray groupUniqArrayArrayIf groupUniqArrayIf grouping h3CellAreaM2 h3CellAreaRads2 h3Distance h3EdgeAngle h3EdgeLengthKm h3EdgeLengthM h3ExactEdgeLengthKm h3ExactEdgeLengthM h3ExactEdgeLengthRads h3GetBaseCell
+h3GetDestinationIndexFromUnidirectionalEdge h3GetFaces h3GetIndexesFromUnidirectionalEdge h3GetOriginIndexFromUnidirectionalEdge h3GetPentagonIndexes h3GetRes0Indexes h3GetResolution h3GetUnidirectionalEdge h3GetUnidirectionalEdgeBoundary h3GetUnidirectionalEdgesFromHexagon h3HexAreaKm2 h3HexAreaM2 h3HexRing h3IndexesAreNeighbors h3IsPentagon h3IsResClassIII h3IsValid h3Line h3NumHexagons h3PointDistKm
+h3PointDistM h3PointDistRads h3ToCenterChild h3ToChildren h3ToGeo h3ToGeoBoundary h3ToParent h3ToString h3UnidirectionalEdgeIsValid h3kRing has hasAll hasAllTokens hasAny hasAnyTokens hasSubsequence hasSubsequenceCaseInsensitive hasSubsequenceCaseInsensitiveUTF8 hasSubsequenceUTF8 hasSubstr
+hasToken hasTokenCaseInsensitive hasTokenCaseInsensitiveOrNull hasTokenOrNull hex hop hopEnd hopStart hypot if ifNotFinite ifnull ilike in indexHint indexOf initcap intDiv intDivOrZero intExp10
+intExp2 isFinite isIPAddressInRange isIPv4String isIPv6String isInfinite isLikelyBot isNaN isNotNull isValidJSON isValidUTF8 isnull jev json_agg kurtPop kurtPopIf kurtSamp kurtSampIf lag lagInFrame
+languageCodeToName last_value lcm lead leadInFrame least left leftPad leftPadUTF8 length lengthUTF8 less lessOrEquals lgamma like ln locate log log10 log1p
+log2 lookupDomainType lookupOrganicMediumType lookupOrganicSourceType lookupPaidMediumType lookupPaidSourceType lower lowerUTF8 lpad ltrim make_date make_interval make_timestamp make_timestamptz map mapAdd mapApply mapContains mapContainsKeyLike mapExists
+mapExtractKeyLike mapFilter mapFromArrays mapKeys mapPopulateSeries mapSubtract mapUpdate mapValues match matchesAction max max2 maxArgMax maxArgMaxIf maxArgMaxOrDefault maxArgMaxOrDefaultIf maxArgMaxOrNull maxArgMaxOrNullIf maxArgMin maxArgMinIf
+maxArgMinOrDefault maxArgMinOrDefaultIf maxArgMinOrNull maxArgMinOrNullIf maxArray maxArrayIf maxArrayOrDefault maxArrayOrDefaultIf maxArrayOrNull maxArrayOrNullIf maxForEach maxForEachIf maxForEachOrDefault maxForEachOrDefaultIf maxForEachOrNull maxForEachOrNullIf maxIf maxIntersections maxIntersectionsIf maxIntersectionsPosition
+maxIntersectionsPositionIf maxMap maxMapIf maxMapOrDefault maxMapOrDefaultIf maxMapOrNull maxMapOrNullIf maxMerge maxMergeIf maxMergeOrDefault maxMergeOrDefaultIf maxMergeOrNull maxMergeOrNullIf maxOrDefault maxOrDefaultIf maxOrNull maxOrNullIf maxState maxStateIf maxStateOrDefault
+maxStateOrDefaultIf maxStateOrNull maxStateOrNullIf md5 median medianArgMax medianArgMaxIf medianArgMaxOrDefault medianArgMaxOrDefaultIf medianArgMaxOrNull medianArgMaxOrNullIf medianArgMin medianArgMinIf medianArgMinOrDefault medianArgMinOrDefaultIf medianArgMinOrNull medianArgMinOrNullIf medianArray medianArrayIf medianArrayOrDefault
+medianArrayOrDefaultIf medianArrayOrNull medianArrayOrNullIf medianBFloat16 medianBFloat16If medianDeterministic medianDeterministicIf medianExact medianExactHigh medianExactHighIf medianExactIf medianExactLow medianExactLowIf medianExactWeighted medianExactWeightedIf medianForEach medianForEachIf medianForEachOrDefault medianForEachOrDefaultIf medianForEachOrNull
+medianForEachOrNullIf medianIf medianMap medianMapIf medianMapOrDefault medianMapOrDefaultIf medianMapOrNull medianMapOrNullIf medianMerge medianMergeIf medianMergeOrDefault medianMergeOrDefaultIf medianMergeOrNull medianMergeOrNullIf medianOrDefault medianOrDefaultIf medianOrNull medianOrNullIf medianState medianStateIf
+medianStateOrDefault medianStateOrDefaultIf medianStateOrNull medianStateOrNullIf medianTDigest medianTDigestIf medianTDigestWeighted medianTDigestWeightedIf medianTiming medianTimingIf medianTimingWeighted medianTimingWeightedIf min min2 minArgMax minArgMaxIf minArgMaxOrDefault minArgMaxOrDefaultIf minArgMaxOrNull minArgMaxOrNullIf
+minArgMin minArgMinIf minArgMinOrDefault minArgMinOrDefaultIf minArgMinOrNull minArgMinOrNullIf minArray minArrayIf minArrayOrDefault minArrayOrDefaultIf minArrayOrNull minArrayOrNullIf minForEach minForEachIf minForEachOrDefault minForEachOrDefaultIf minForEachOrNull minForEachOrNullIf minIf minMap
+minMapIf minMapOrDefault minMapOrDefaultIf minMapOrNull minMapOrNullIf minMerge minMergeIf minMergeOrDefault minMergeOrDefaultIf minMergeOrNull minMergeOrNullIf minOrDefault minOrDefaultIf minOrNull minOrNullIf minState minStateIf minStateOrDefault minStateOrDefaultIf minStateOrNull
+minStateOrNullIf minus modulo moduloOrZero monthName multiFuzzyMatchAllIndices multiFuzzyMatchAny multiFuzzyMatchAnyIndex multiIf multiMatchAllIndices multiMatchAny multiMatchAnyIndex multiSearchAllPositions multiSearchAllPositionsCaseInsensitive multiSearchAllPositionsCaseInsensitiveUTF8 multiSearchAllPositionsUTF8 multiSearchAny multiSearchAnyCaseInsensitive multiSearchAnyCaseInsensitiveUTF8 multiSearchAnyUTF8
+multiSearchFirstIndex multiSearchFirstIndexCaseInsensitive multiSearchFirstIndexCaseInsensitiveUTF8 multiSearchFirstIndexUTF8 multiSearchFirstPosition multiSearchFirstPositionCaseInsensitive multiSearchFirstPositionCaseInsensitiveUTF8 multiSearchFirstPositionUTF8 multiply multiplyDecimal negate netloc ngramDistance ngramDistanceCaseInsensitive ngramDistanceCaseInsensitiveUTF8 ngramDistanceUTF8 ngramSearch ngramSearchCaseInsensitive ngramSearchCaseInsensitiveUTF8 ngramSearchUTF8
+ngrams not notEmpty notEquals notILike notIn notLike now nowInBlock nth_value nullif or parseDateTime parseDateTimeBestEffort path pathFull percentile_cont percentile_disc pi plus
+pointInEllipses pointInPolygon port position positionCaseInsensitive positionCaseInsensitiveUTF8 positionUTF8 positiveModulo pow power protocol quantile quantileExact quantileIf quantiles quantilesIf quantilesMerge quantilesMergeIf quantilesState quantilesStateIf
+queryString queryStringAndFragment radians rand range rank recordingButton regexpExtract regexpQuoteMeta reinterpretAsFloat32 reinterpretAsFloat64 reinterpretAsInt128 reinterpretAsInt16 reinterpretAsInt256 reinterpretAsInt32 reinterpretAsInt64 reinterpretAsInt8 reinterpretAsUInt128 reinterpretAsUInt16 reinterpretAsUInt256
+reinterpretAsUInt32 reinterpretAsUInt64 reinterpretAsUInt8 reinterpretAsUUID repeat replace replaceAll replaceOne replaceRegexpAll replaceRegexpOne reverse reverseUTF8 right rightPad rightPadUTF8 round roundAge roundBankers roundDown roundDuration
+roundToExp2 rowNumberInAllBlocks rowNumberInBlock row_number rpad rtrim sign simpleLinearRegression simpleLinearRegressionIf sin sinh skewPop skewPopIf skewSamp skewSampIf sortablesemver sparkline splitByChar splitByNonAlpha splitByRegexp
+splitByString splitByWhitespace split_part sqrt startsWith stddevPop stddevPopIf stddevSamp stddevSampIf stringToH3 string_agg subBitmap substring substringUTF8 subtractDays subtractHours subtractMinutes subtractMonths subtractQuarters subtractSeconds
+subtractWeeks subtractYears sum sumArgMax sumArgMaxIf sumArgMaxOrDefault sumArgMaxOrDefaultIf sumArgMaxOrNull sumArgMaxOrNullIf sumArgMin sumArgMinIf sumArgMinOrDefault sumArgMinOrDefaultIf sumArgMinOrNull sumArgMinOrNullIf sumArray sumArrayIf sumArrayOrDefault sumArrayOrDefaultIf sumArrayOrNull
+sumArrayOrNullIf sumForEach sumForEachIf sumForEachMerge sumForEachOrDefault sumForEachOrDefaultIf sumForEachOrNull sumForEachOrNullIf sumForEachState sumIf sumMap sumMapIf sumMapMerge sumMapMergeIf sumMapOrDefault sumMapOrDefaultIf sumMapOrNull sumMapOrNullIf sumMerge sumMergeIf
+sumMergeOrDefault sumMergeOrDefaultIf sumMergeOrNull sumMergeOrNullIf sumOrDefault sumOrDefaultIf sumOrNull sumOrNullIf sumState sumStateIf sumStateOrDefault sumStateOrDefaultIf sumStateOrNull sumStateOrNullIf sumWithOverflow sumWithOverflowIf tan tgamma theilsU theilsUIf
+throwIf timeSlot timeSlots timeStampAdd timeStampSub timeZoneOf timeZoneOffset timezone toBool toDate toDateTime toDateTime64 toDateTimeUS toDayOfMonth toDayOfWeek toDayOfYear toDecimal toFloat toFloat64OrNull toFloatOrDefault
+toFloatOrNull toFloatOrZero toHour toIPv4 toIPv4OrDefault toIPv4OrNull toIPv4OrZero toIPv6 toIPv6OrDefault toIPv6OrNull toIPv6OrZero toISOWeek toISOYear toInt toIntOrDefault toIntOrZero toIntervalDay toIntervalHour toIntervalMinute toIntervalMonth
+toIntervalQuarter toIntervalSecond toIntervalWeek toIntervalYear toJSONString toLastDayOfMonth toLastDayOfWeek toMinute toModifiedJulianDay toMonday toMonth toNullable toNullableString toQuarter toSecond toStartOfDay toStartOfFifteenMinutes toStartOfFiveMinutes toStartOfHour toStartOfISOYear
+toStartOfInterval toStartOfMinute toStartOfMonth toStartOfQuarter toStartOfSecond toStartOfTenMinutes toStartOfWeek toStartOfYear toString toTime toTimeZone toTypeName toUUID toUUIDOrDefault toUnixTimestamp toUnixTimestamp64Milli toValidUTF8 toWeek toYYYYMM toYYYYMMDD
+toYYYYMMDDhhmmss toYear toYearWeek to_char to_date to_timestamp today tokens topK topLevelDomain transform translate translateUTF8 trim trimLeft trimRight trunc tryBase58Decode tryBase64Decode tumble
+tumbleEnd tumbleStart tuple tupleDivide tupleDivideByNumber tupleElement tupleHammingDistance tupleMinus tupleMultiply tupleMultiplyByNumber tupleNegate tuplePlus tupleToNameValuePairs unhex uniq uniqCombined uniqCombined64 uniqExact uniqExactIf uniqExactMerge
+uniqExactState uniqHLL12 uniqHLL12If uniqIf uniqMap uniqMapMerge uniqMapMergeIf uniqMerge uniqMergeIf uniqState uniqStateIf uniqTheta uniqThetaIf uniqUpToMerge uniqueSurveySubmissionsFilter untuple upper upperUTF8 varPop varPopIf
+varSamp varSampIf width_bucket windowFunnel xor yesterday
`)
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index eb5fe4705bce..90efd12b44fa 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -10703,6 +10703,21 @@ export namespace Schemas {
key: string;
}
+ export interface BITopN {
+ /** @minimum 1 */
+ count: number;
+ fieldId: string;
+ includeOther: boolean;
+ /** @minimum 0 */
+ measureIndex: number;
+ }
+
+ export interface BITotals {
+ columns?: boolean | null;
+ rows?: boolean | null;
+ subtotals?: boolean | null;
+ }
+
export type BIAggregation = typeof BIAggregation[keyof typeof BIAggregation];
@@ -10716,11 +10731,32 @@ export namespace Schemas {
Custom: 'custom',
} as const;
+ export type BITableCalculationType = typeof BITableCalculationType[keyof typeof BITableCalculationType];
+
+
+ export const BITableCalculationType = {
+ PercentOfTotal: 'percent_of_total',
+ RunningTotal: 'running_total',
+ Difference: 'difference',
+ PercentChange: 'percent_change',
+ MovingAverage: 'moving_average',
+ Rank: 'rank',
+ } as const;
+
+ export interface BITableCalculation {
+ /** Dimension ID to traverse. Unset chooses the date dimension; 'table' traverses all dimensions. */
+ computeUsing?: string | null;
+ type: BITableCalculationType;
+ /** Number of points, including the current point, in a trailing moving average. */
+ window?: number | null;
+ }
+
export interface BIValue {
aggregation: BIAggregation;
customExpression?: string | null;
field: BIField;
label?: string | null;
+ tableCalculation?: BITableCalculation | null;
}
export interface BIConfig {
@@ -10736,6 +10772,8 @@ export namespace Schemas {
/** null sorts automatically: newest date or highest value first, so top rows survive the LIMIT. */
sort?: BISort | null;
source?: BIDataSource | null;
+ topN?: BITopN | null;
+ totals?: BITotals | null;
values: BIValue[];
}