MODE WITHIN GROUP Picks Most Frequent Value
Return the most frequent non-null value per group with mode() WITHIN GROUP, and narrow the vote with FILTER when only qualifying rows count.
Code
-- mode() WITHIN GROUP returns the most frequent non-NULL value (the mode)
-- ties return one of the tied values, unspecified which: report copy must not claim a single winner
CREATE TEMP TABLE sales (
region text NOT NULL,
channel text NOT NULL,
amount numeric NOT NULL
);
INSERT INTO sales (region, channel, amount) VALUES
('emea', 'web', 120), ('emea', 'web', 80), ('emea', 'api', 300),
('apac', 'api', 90), ('apac', 'web', 140), ('apac', 'api', 60);
SELECT
region,
mode() WITHIN GROUP (ORDER BY channel) AS top_channel,
-- FILTER works for ordered-set aggregates too: only qualifying orders get a vote
mode() WITHIN GROUP (ORDER BY channel)
FILTER (WHERE amount >= 100) AS big_order_channel,
-- sample size signals how much to trust the mode: two of three leading is not the same as a three-way tie
count(*) AS samples
FROM sales
GROUP BY region
ORDER BY region;How it works
Several statements share this file — SELECT / INSERT / CREATE, with sales among the objects involved.
sales is created in this same file as session-local temp tables — nothing needs to exist beforehand, and it goes away at session end.
Breaking the statements into their working parts: a WHERE clause narrowing which rows one statement affects; COUNT aggregation; a GROUP BY that collapses matching rows into one output row per group; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns.
Applying it
The file is self-contained: it creates the session-local tables it uses (sales), so run it as a whole against a scratch database.
Statements that matter
SELECT
region,
mode() WITHIN GROUP (ORDER BY channel) AS top_channel,
mode() WITHIN GROUP (ORDER BY channel)
FILTER (WHERE amount >= 100) AS big_order_channel,
count(*) AS samples
FROM sales
GROUP BY region
ORDER BY region;
INSERT INTO sales (region, channel, amount) VALUES
('emea', 'web', 120), ('emea', 'web', 80), ('emea', 'api', 300),
('apac', 'api', 90), ('apac', 'web', 140), ('apac', 'api', 60);
CREATE TEMP TABLE sales (
region text NOT NULL,
channel text NOT NULL,
amount numeric NOT NULL
);
Interactive Tools for This Topic
FAQ
- Which tables or CTEs does it reference?
- The references are `sales`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.