WITH grouped AS (
    SELECT {group_col} AS value_label, COUNT(*) AS support
    FROM {table}
    GROUP BY {group_col}
), ranked AS (
    SELECT
        value_label,
        support,
        CAST(support AS FLOAT) / NULLIF(SUM(support) OVER (), 0) AS support_share,
        SUM(support) OVER (ORDER BY support DESC, value_label ROWS UNBOUNDED PRECEDING) AS cumulative_support
    FROM grouped
)
SELECT *
FROM ranked
ORDER BY support DESC, value_label;

Locally authored v2 template

Locally authored v2 template


SELECT
    {key_col},
    COUNT(*) AS support,
    AVG({measure_col}) AS avg_response
FROM {table}
GROUP BY {key_col}
HAVING COUNT(*) >= {min_support}
ORDER BY support DESC, avg_response DESC;

Locally authored v2 template

Locally authored v2 template


WITH grouped AS (
    SELECT {group_col} AS value_label, COUNT(*) AS support
    FROM {table}
    GROUP BY {group_col}
)
SELECT
    value_label,
    support,
    CAST(support AS FLOAT) / NULLIF(SUM(support) OVER (), 0) AS support_share,
    ROW_NUMBER() OVER (ORDER BY support DESC, value_label) AS support_rank
FROM grouped
ORDER BY support DESC, value_label;

Locally authored v2 template

Locally authored v2 template


Count rows for a filtered slice across two subgroup dimensions.

SELECT {group_col}, {group_col_2}, COUNT(*) AS row_count
FROM {table}
WHERE {predicate_col} {predicate_op} {predicate_value}
GROUP BY {group_col}, {group_col_2}
ORDER BY row_count DESC;

Answers.sql · Exploratory-Analysis-of-Car-Evaluation-Dataset-with-SQL

Useful as a general “slice then compare subgroups” template.


Measure how a categorical target rate changes across a pair of subgroup axes.

SELECT {group_col}, {group_col_2},
       AVG(CASE WHEN {target_col} = {target_value} THEN 1 ELSE 0 END) AS target_rate
FROM {table}
GROUP BY {group_col}, {group_col_2}
ORDER BY target_rate DESC;

Strong fit for classification-style single-table datasets; partial on regression tasks.


Report subgroup percentile points only for rows satisfying a low-cardinality condition.

SELECT {group_col},
       PERCENTILE_CONT({percentile_value}) WITHIN GROUP (ORDER BY {measure_col})
           FILTER (WHERE {condition_col} = {condition_value}) AS conditional_percentile
FROM {table}
GROUP BY {group_col}
ORDER BY conditional_percentile DESC;

quantilesTimingIf | ClickHouse Docs

quantilesTimingIf | ClickHouse Docs

Kept optional because it is highly valuable for observability-style tails but more dialect-sensitive than the rest of the core library.

Uses percentile syntax plus conditional aggregation/filter semantics. Keep it optional unless the downstream engine supports ordered-set percentiles and FILTER/If-style conditioning.


Bin a numeric feature into coarse buckets and compare average outcomes across those bins.

SELECT CASE
           WHEN {band_col} < {band_cut_1} THEN 'low'
           WHEN {band_col} < {band_cut_2} THEN 'mid'
           ELSE 'high'
       END AS band_bucket,
       AVG({measure_col}) AS avg_measure
FROM {table}
GROUP BY band_bucket
ORDER BY avg_measure DESC;

Analysis_queries.sql · insurance-sql-analysis

Important for numeric-heavy datasets where raw continuous features must be discretized before subgroup reasoning.


Estimate the proportion of rows meeting a low-cardinality condition within each subgroup.

SELECT {group_col},
       AVG(CASE WHEN {condition_col} = {condition_value} THEN 1 ELSE 0 END) AS condition_rate
FROM {table}
GROUP BY {group_col}
ORDER BY condition_rate DESC;

Insurance cost SQL analysis.sql · Insurance-Cost-Project-Using-SQL

Strong analytics template for subgroup-conditional proportions with broad portability.


Rank subgroups by within-group dispersion of a numeric measure.

SELECT {group_col}, STDDEV({measure_col}) AS measure_stddev
FROM {table}
GROUP BY {group_col}
ORDER BY measure_stddev DESC
LIMIT {top_k};

Expands beyond mean-only summaries into spread-sensitive analytics.


Contrast two condition counts within each subgroup as a ratio.

WITH grouped AS (
    SELECT {group_col},
           SUM(CASE WHEN {condition_col} = {positive_value} THEN 1 ELSE 0 END) AS numerator_count,
           SUM(CASE WHEN {condition_col} = {negative_value} THEN 1 ELSE 0 END) AS denominator_count
    FROM {table}
    GROUP BY {group_col}
)
SELECT {group_col},
       CAST(numerator_count AS FLOAT) / NULLIF(denominator_count, 0) AS condition_ratio
FROM grouped
ORDER BY condition_ratio DESC;

Captures a common dashboard KPI style rather than a benchmark-only artifact.


Compute a median-like robust center for a filtered numeric slice.

WITH ranked AS (
    SELECT {measure_col},
           ROW_NUMBER() OVER (ORDER BY {measure_col}) AS row_num,
           COUNT(*) OVER () AS total_rows
    FROM {table}
    WHERE {predicate_col} {predicate_op} {predicate_value}
)
SELECT AVG({measure_col}) AS median_measure
FROM ranked
WHERE row_num BETWEEN (total_rows + 1) / 2 AND (total_rows + 2) / 2;

Retained because robust-statistic templates are common in practical analytical workflows even if they are not universal.


Use a window function to report per-group averages without collapsing the row-level relation first.

SELECT DISTINCT {group_col},
       AVG({measure_col}) OVER (PARTITION BY {group_col}) AS avg_measure
FROM {table}
ORDER BY avg_measure DESC;

Adds explicit window-function coverage to the analytics library.


Count events per time bucket within a filtered slice.

SELECT DATE_TRUNC('{time_grain}', {time_col}) AS time_bucket,
       COUNT(*) AS event_count
FROM {table}
WHERE {predicate_col} {predicate_op} {predicate_value}
GROUP BY time_bucket
ORDER BY time_bucket;

postgres/queries/0004_count_delayed_orders_per_day.sql · RTABench

Added as a restrained time-aware extension because time-bucket event counts are one of the most universal temporal dashboard queries.


Compute a rolling moving average over time-bucketed subgroup counts.

WITH bucketed AS (
    SELECT DATE_TRUNC('{time_grain}', {time_col}) AS time_bucket,
           {group_col},
           COUNT(*) AS event_count
    FROM {table}
    WHERE {predicate_col} {predicate_op} {predicate_value}
    GROUP BY time_bucket, {group_col}
)
SELECT time_bucket,
       {group_col},
       event_count,
       AVG(event_count) OVER (
           PARTITION BY {group_col}
           ORDER BY time_bucket
           ROWS BETWEEN {lookback_rows} PRECEDING AND CURRENT ROW
       ) AS moving_avg_count
FROM bucketed
ORDER BY {group_col}, time_bucket;

postgres/queries/0000_terminal_hourly_stats.sql · RTABench

Represents a common dashboard smoothing pattern while staying within a single-table event log structure.


Compare current-period to prior-period subgroup volume and flag material negative drift.

WITH period_counts AS (
    SELECT {group_col},
           SUM(CASE WHEN {time_col} >= {current_period_start} AND {time_col} < {current_period_end} THEN 1 ELSE 0 END) AS current_count,
           SUM(CASE WHEN {time_col} >= {previous_period_start} AND {time_col} < {previous_period_end} THEN 1 ELSE 0 END) AS previous_count
    FROM {table}
    GROUP BY {group_col}
)
SELECT {group_col}, current_count, previous_count,
       CAST(current_count AS FLOAT) / NULLIF(previous_count, 0) AS drift_ratio
FROM period_counts
WHERE CAST(current_count AS FLOAT) / NULLIF(previous_count, 0) < {drift_ratio_threshold}
ORDER BY drift_ratio ASC;

query_75.sql · Altinity/tpc-ds

query_75.sql · Altinity/tpc-ds

Explicitly kept in the extension bucket because most current benchmark datasets lack real temporal semantics.


Apply a subgroup baseline gate before ranking entities by an extreme aggregate outcome.

WITH item_stats AS (
    SELECT {group_col}, {item_col}, AVG({measure_col}) AS avg_measure
    FROM {table}
    GROUP BY {group_col}, {item_col}
), group_baseline AS (
    SELECT {group_col}, AVG(avg_measure) AS group_avg
    FROM item_stats
    GROUP BY {group_col}
), eligible AS (
    SELECT i.{group_col}, i.{item_col}, i.avg_measure
    FROM item_stats AS i
    JOIN group_baseline AS g
      ON i.{group_col} = g.{group_col}
    WHERE i.avg_measure > g.group_avg * {baseline_fraction}
)
SELECT {group_col}, {item_col}, avg_measure,
       RANK() OVER (PARTITION BY {group_col} ORDER BY avg_measure DESC) AS within_group_rank
FROM eligible
ORDER BY avg_measure DESC
LIMIT {top_k};

query_44.sql · Altinity/tpc-ds

query_44.sql · Altinity/tpc-ds

Distinct from plain top-k because the ranking only happens after a relative baseline gate is cleared.


Measure each item's contribution within a parent subgroup using a windowed share-of-total.

SELECT {group_col}, {item_col},
       SUM({measure_col}) AS total_measure,
       SUM({measure_col}) * 100.0 / SUM(SUM({measure_col})) OVER (PARTITION BY {group_col}) AS share_within_group
FROM {table}
GROUP BY {group_col}, {item_col}
ORDER BY share_within_group DESC;

query_qualification/98.sql · tpcds-result-reproduction

One of the strongest workload-grounded window templates retained in v1.


Aggregate a numeric measure within a numeric band filter.

SELECT SUM({measure_col}) AS total_measure
FROM {table}
WHERE {band_col} BETWEEN {lower_bound} AND {upper_bound};

queries/6.sql · tpch-dbgen

queries/6.sql · tpch-dbgen

Promoted into the materialized core because the tail review showed this narrow-band threshold slice is a canonical low-support but high-impact pattern rather than a benchmark curiosity.


SELECT
    COUNT(*) AS total_rows,
    SUM(CASE WHEN {missing_col} IS NULL THEN 1 ELSE 0 END) AS missing_rows,
    AVG(CASE WHEN {missing_col} IS NULL THEN 1.0 ELSE 0.0 END) AS missing_rate
FROM {table};

Locally authored v2 template

Locally authored v2 template


SELECT
    {group_col},
    COUNT(*) AS total_rows,
    SUM(CASE WHEN {missing_col} IS NULL THEN 1 ELSE 0 END) AS missing_rows,
    AVG(CASE WHEN {missing_col} IS NULL THEN 1.0 ELSE 0.0 END) AS missing_rate
FROM {table}
GROUP BY {group_col}
ORDER BY missing_rate DESC, total_rows DESC;

Locally authored v2 template

Locally authored v2 template


SELECT
    {target_col},
    COUNT(*) AS total_rows,
    SUM(CASE WHEN {missing_col} IS NULL THEN 1 ELSE 0 END) AS missing_rows,
    AVG(CASE WHEN {missing_col} IS NULL THEN 1.0 ELSE 0.0 END) AS missing_rate
FROM {table}
GROUP BY {target_col}
ORDER BY missing_rate DESC, total_rows DESC;

Locally authored v2 template

Locally authored v2 template


Rank subgroups by distinct-entity coverage within a filtered slice.

SELECT {group_col}, COUNT(DISTINCT {entity_col}) AS distinct_entities
FROM {table}
WHERE {predicate_col} {predicate_op} {predicate_value}
GROUP BY {group_col}
ORDER BY distinct_entities DESC
LIMIT {top_k};

clickhouse/queries.sql · ClickBench

clickhouse/queries.sql · ClickBench

A broadly useful dashboard pattern that combines slicing with distinct-user style coverage ranking.


Rank subgroups by support within a filtered slice.

SELECT {group_col}, COUNT(*) AS support
FROM {table}
WHERE {predicate_col} {predicate_op} {predicate_value}
GROUP BY {group_col}
ORDER BY support DESC
LIMIT {top_k};

clickhouse/queries.sql · ClickBench

clickhouse/queries.sql · ClickBench

A cleaner heavy-hitter slice than the existing two-dimensional filtered count template.


Count rows by a single subgroup dimension to capture baseline subgroup mass.

SELECT {group_col}, COUNT(*) AS row_count
FROM {table}
GROUP BY {group_col}
ORDER BY row_count DESC;

clickhouse/queries.sql · ClickBench

clickhouse/queries.sql · ClickBench

Closest to dashboard-style subgroup mass queries; deliberately keeps only one group axis for broad portability.


Top-k Groups by Distinct Entity Coverage

Find the top subgroups by distinct-entity coverage.

SELECT {group_col}, COUNT(DISTINCT {entity_col}) AS distinct_entities
FROM {table}
GROUP BY {group_col}
ORDER BY distinct_entities DESC
LIMIT {top_k};

clickhouse/queries.sql · ClickBench

clickhouse/queries.sql · ClickBench

Good proxy for coverage/richness queries seen in web analytics workloads.


Rank subgroups by support while also reporting a numeric mean and distinct-entity coverage.

SELECT {group_col},
       COUNT(*) AS support,
       AVG({measure_col}) AS avg_measure,
       COUNT(DISTINCT {entity_col}) AS distinct_entities
FROM {table}
GROUP BY {group_col}
ORDER BY support DESC
LIMIT {top_k};

clickhouse/queries.sql · ClickBench

clickhouse/queries.sql · ClickBench

Retains the multi-metric dashboard feel of ClickBench without overfitting to web-log column names.


Find the heaviest two-dimensional subgroup combinations by row count.

SELECT {group_col}, {group_col_2}, COUNT(*) AS support
FROM {table}
GROUP BY {group_col}, {group_col_2}
ORDER BY support DESC
LIMIT {top_k};

clickhouse/queries.sql · ClickBench

clickhouse/queries.sql · ClickBench

Useful for interaction-heavy dashboards and joint heavy-hitter analysis.


Compare total numeric mass across subgroups using a simple grouped sum.

SELECT {group_col}, SUM({measure_col}) AS total_measure
FROM {table}
GROUP BY {group_col}
ORDER BY total_measure DESC;

duckdb/groupby-duckdb.R · h2oai/db-benchmark

Selected because plain grouped sums are missing from the current library yet are among the most universal single-table analytics queries.


Compare total numeric mass across a two-way subgroup grid.

SELECT {group_col}, {group_col_2}, SUM({measure_col}) AS total_measure
FROM {table}
GROUP BY {group_col}, {group_col_2}
ORDER BY total_measure DESC;

Complements the existing two-dimensional count and average templates with the equally common summed-mass view.


Compare robust center and spread of a numeric measure across a two-way subgroup grid.

SELECT {group_col}, {group_col_2},
       PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY {measure_col}) AS median_measure,
       STDDEV({measure_col}) AS measure_stddev
FROM {table}
GROUP BY {group_col}, {group_col_2}
ORDER BY median_measure DESC;

Kept in the core registry as an optional analytics template. It is dialect-sensitive because ordered-set percentile support varies across SQL engines.

Uses ordered-set percentile and standard-deviation aggregates. Keep it optional unless the downstream SQL engine supports PERCENTILE_CONT/QUANTILE_CONT-style syntax.


Compare mean numeric outcomes across subgroups.

SELECT {group_col}, AVG({measure_col}) AS avg_measure
FROM {table}
GROUP BY {group_col}
ORDER BY avg_measure DESC;

One of the most reusable regression-style templates among the public insurance SQL repository exemplars.


Compute subgroup averages only when support exceeds a configurable minimum.

SELECT {group_col}, AVG({measure_col}) AS avg_measure, COUNT(*) AS support
FROM {table}
GROUP BY {group_col}
HAVING COUNT(*) > {min_group_size}
ORDER BY {group_col};

Reclassified as analytics because the support guard is part of the query semantics rather than an external evaluation rule.


Compare average numeric outcomes across a two-way subgroup grid.

SELECT {group_col}, {group_col_2}, AVG({measure_col}) AS avg_measure
FROM {table}
GROUP BY {group_col}, {group_col_2}
ORDER BY avg_measure DESC;

Clean public-repo analogue of pairwise interaction reporting.


Rank groups by weighted aggregate mass while preserving both support and weighted total.

SELECT {group_col},
       SUM({measure_col}) AS weighted_total,
       COUNT(*) AS support
FROM {table}
GROUP BY {group_col}
HAVING COUNT(*) >= {min_support}
ORDER BY weighted_total DESC
LIMIT {top_k};

Approximate aggregate functions | BigQuery | Google Cloud Documentation

approx_top_sum | ClickHouse Docs

Materialized as a canonical family rather than an engine-specific function variant, with BigQuery and ClickHouse as independent public evidence sources.


Rank subgroups by total numeric measure under a filter.

SELECT {group_col}, SUM({measure_col}) AS total_measure
FROM {table}
WHERE {predicate_col} {predicate_op} {predicate_value}
GROUP BY {group_col}
ORDER BY total_measure DESC
LIMIT {top_k};

query_qualification/03.sql · tpcds-result-reproduction

A pragmatic single-table reduction of a common sales-ranking pattern.


Aggregate by group and keep only the winner whose aggregate value is maximal.

WITH grouped AS (
    SELECT {group_col}, SUM({measure_col}) AS total_measure
    FROM {table}
    GROUP BY {group_col}
)
SELECT {group_col}, total_measure
FROM grouped
WHERE total_measure = (SELECT MAX(total_measure) FROM grouped)
ORDER BY {group_col};

queries/15.sql · electrum/tpch-dbgen

queries/15.sql · electrum/tpch-dbgen

Distinct from ordinary top-k because it encodes winner-only selection after grouped aggregation.


Summarize a numeric measure across two grouping axes with an additional filter.

SELECT {group_col}, {group_col_2},
       SUM({measure_col}) AS sum_measure,
       AVG({measure_col}) AS avg_measure,
       COUNT(*) AS support
FROM {table}
WHERE {predicate_col} {predicate_op} {predicate_value}
GROUP BY {group_col}, {group_col_2}
ORDER BY {group_col}, {group_col_2};

queries/1.sql · tpch-dbgen

queries/1.sql · tpch-dbgen

Join-free abstraction of a classic TPC-H summary report pattern.


Report a percentile point such as p95 or p99 for each subgroup instead of returning the raw tail rows.

SELECT {group_col},
       PERCENTILE_CONT({percentile_value}) WITHIN GROUP (ORDER BY {measure_col}) AS percentile_measure
FROM {table}
GROUP BY {group_col}
ORDER BY percentile_measure DESC;

Aggregate functions — Trino Documentation

PERCENTILE_CONT | Snowflake Documentation

Snowflake PERCENTILE_CONT grouped example

quantile | ClickHouse Docs

All Druid SQL functions | Apache Druid

percentile | Apache Pinot Docs

Canonical percentile-point family added so the library can represent p95/p99 style tail monitoring without returning full quantile slices.

Represents a canonical percentile-point family, but concrete SQL differs across engines (for example PERCENTILE_CONT, APPROX_QUANTILES, approx_percentile, or quantile-style syntax).


Retain the top-N numeric values within each subgroup using window ranking.

WITH ranked AS (
    SELECT {group_col}, {measure_col},
           ROW_NUMBER() OVER (PARTITION BY {group_col} ORDER BY {measure_col} DESC) AS measure_rank
    FROM {table}
    WHERE {measure_col} IS NOT NULL
)
SELECT {group_col}, {measure_col}, measure_rank
FROM ranked
WHERE measure_rank <= {top_n}
ORDER BY {group_col}, measure_rank;

A canonical window-ranking template from an official single-table benchmark and a good fit for agent-side candidate generation.


Score a numeric measure globally and surface high-z-score outliers.

WITH scored AS (
    SELECT *,
           ({measure_col} - AVG({measure_col}) OVER ())
           / NULLIF(STDDEV({measure_col}) OVER (), 0) AS z_score
    FROM {table}
)
SELECT *
FROM scored
WHERE ABS(z_score) > {z_threshold}
ORDER BY {measure_col} DESC;

Useful for tail-sensitive analytics and anomaly-style reporting.


Select the highest quantile bucket of a numeric measure using NTILE-style ranking.

WITH buckets AS (
    SELECT {measure_col},
           NTILE({num_tiles}) OVER (ORDER BY {measure_col} DESC) AS tail_bucket
    FROM {table}
)
SELECT {measure_col}
FROM buckets
WHERE tail_bucket = 1
ORDER BY {measure_col} DESC;

A high-value tail template because it expresses rarity through quantile structure rather than an arbitrary threshold.


New v2 agent template for count-based tail coverage on non-numeric datasets.

SELECT
    {group_col},
    COUNT(*) AS support
FROM {table}
GROUP BY {group_col}
ORDER BY support ASC, {group_col}
LIMIT {top_k};

Locally authored v2 template

Locally authored v2 template


New v2 agent template for sparse pairwise tail slices.

SELECT
    {group_col},
    {group_col_2},
    COUNT(*) AS support
FROM {table}
GROUP BY {group_col}, {group_col_2}
ORDER BY support ASC, {group_col}, {group_col_2}
LIMIT {top_k};

Locally authored v2 template

Locally authored v2 template


New v2 agent template for classification-style tail concentration coverage.

SELECT
    {group_col},
    COUNT(*) AS support,
    AVG(CASE WHEN {target_col} = {target_value} THEN 1 ELSE 0 END) AS focus_rate
FROM {table}
GROUP BY {group_col}
HAVING COUNT(*) >= {min_support}
ORDER BY focus_rate DESC, support ASC
LIMIT {top_k};

Locally authored v2 template

Locally authored v2 template


Estimate how rare a threshold is by reporting the empirical CDF value at that threshold.

SELECT AVG(CASE WHEN {measure_col} <= {measure_threshold} THEN 1 ELSE 0 END) AS empirical_cdf_at_threshold
FROM {table};

All Druid SQL functions | Apache Druid

All Druid SQL functions | Apache Druid

Added because it answers a different question from percentile-point queries: not 'what is p99?' but 'how rare is threshold T?'


Find entity-level aggregates that are extreme relative to their own subgroup baseline.

WITH entity_totals AS (
    SELECT {group_col}, {item_col}, SUM({measure_col}) AS entity_measure
    FROM {table}
    GROUP BY {group_col}, {item_col}
), subgroup_baseline AS (
    SELECT {group_col}, AVG(entity_measure) AS subgroup_avg
    FROM entity_totals
    GROUP BY {group_col}
)
SELECT e.{group_col}, e.{item_col}, e.entity_measure, b.subgroup_avg
FROM entity_totals AS e
JOIN subgroup_baseline AS b
  ON e.{group_col} = b.{group_col}
WHERE e.entity_measure > b.subgroup_avg * {baseline_multiplier}
ORDER BY e.entity_measure DESC;

query_1.sql · Altinity/tpc-ds

query_1.sql · Altinity/tpc-ds

High-value because it captures rarity relative to a local subgroup baseline, not just global magnitude.


Keep only groups whose aggregate value exceeds a configurable fraction of the grand total.

WITH grouped AS (
    SELECT {group_col}, SUM({measure_col}) AS group_value
    FROM {table}
    GROUP BY {group_col}
), total AS (
    SELECT SUM(group_value) AS total_value
    FROM grouped
)
SELECT g.{group_col}, g.group_value
FROM grouped AS g
CROSS JOIN total AS t
WHERE g.group_value > t.total_value * {fraction_threshold}
ORDER BY g.group_value DESC;

queries/11.sql · electrum/tpch-dbgen

queries/11.sql · electrum/tpch-dbgen

Canonical low-support but high-impact segment template: entity value above a tiny fraction of total.


Rank only those groups whose aggregate value exceeds an explicit threshold.

SELECT {group_col}, SUM({measure_col}) AS total_measure
FROM {table}
GROUP BY {group_col}
HAVING SUM({measure_col}) > {measure_threshold}
ORDER BY total_measure DESC
LIMIT {top_k};

queries/18.sql · electrum/tpch-dbgen

queries/18.sql · electrum/tpch-dbgen

Separates true large-segment ranking from ordinary support guards by thresholding the aggregate itself.