runtime
44 / 88

lesson 44 Window functions · advanced

Share of total with windows

Compare each row with its group total.

the idea

An aggregate window without GROUP BY can put a grand total alongside each group. Aggregate per model first, then use SUM(request_count) OVER() as the denominator.

tables in this lesson

The challenges use this data. Each column shows its type underneath; → marks a link to another table.

ai_requests7 columns · 12 rows
idinteger · keyaccount_idintegermodeltextrequested_attextinput_tokensintegeroutput_tokensintegerstatustext
11swift2025-01-01 10:00:001000200success
21reason2025-01-02 11:00:002000600success
32swift2025-01-02 12:00:005000error
43reason2025-01-02 13:00:0080002000success
53swift2025-01-03 14:00:0040001000success

showing 5 of 12 rows

example

The idea in one query. Press Run to see what it returns; running examples never affects your progress.

example.sql
WITH counts AS(
  SELECT model,COUNT(*) AS request_count
  FROM ai_requests
  GROUP BY model
)
SELECT
  model,
  request_count,
  ROUND(100.0*request_count/ SUM(request_count) OVER(),2) AS share_pct
FROM counts;

Watch for: Partitioning by model would give each model 100%.

build it step by step

Each step changes one thing. Run them in order and watch the result change.

  1. Count requests per model. A share of total needs each group's count and the grand total. Start from the per-model counts.

    step-1.sql
    SELECT model, COUNT(*) AS request_count
    FROM ai_requests
    GROUP BY model
    ORDER BY model;
  2. Divide each count by the window total. A window SUM over the model counts supplies the denominator so each row can show its share.

    step-2.sql
    WITH counts AS (
      SELECT model, COUNT(*) AS request_count
      FROM ai_requests
      GROUP BY model
    )
    SELECT
      model,
      request_count,
      ROUND(1.0 * request_count / SUM(request_count) OVER (), 3) AS share
    FROM counts;

challenge 1

Return model, request_count and share_pct (0–100, 2 decimals) for all request rows by model.

Return modelrequest_countshare_pctany row order

challenge-1.sql
 
To master this lesson, solve both challenges without hints and pass the concept check. 3 of 3 to go.