SQL Reporting Techniques: Buckets, Histograms, Shares and Running Percentages
Report-building techniques in SQL: grouping values into bands with CASE, WIDTH_BUCKET and NTILE, text histograms, percentages of a total and of a group, running percentages and ABC analysis, top N with an "other" row, and labelled subtotal reports with ROLLUP.
kvi5hnuCode Sprout team member9 min readOn this page
Reports rarely show raw rows. They answer questions like "how many products in each price band?", "what share of revenue does each category bring?", "which few products make up most of our sales?" and "the top two categories, and everything else". Each question has a standard SQL shape, built from tools covered earlier: CASE, GROUP BY, window functions and ROLLUP.
This article collects those shapes. The examples use the shop's products table and the sales view (article 20), and most leave out the cancelled order.
Bands with CASE
To count values in ranges, map each value to a band, then group by the band:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- Price bands with CASE: the first matching WHEN wins, so test in order
SELECT CASE WHEN price < 25 THEN '1: under 25'
WHEN price < 100 THEN '2: 25 to 99.99'
WHEN price < 300 THEN '3: 100 to 299.99'
ELSE '4: 300 and over'
END AS price_band,
COUNT(*) AS products,
string_agg(name, ', ' ORDER BY price) AS names
FROM products
GROUP BY price_band
ORDER BY price_band;
-- Equal-width buckets with WIDTH_BUCKET(value, low, high, count)
SELECT name, price,
WIDTH_BUCKET(price, 0, 500, 5) AS bucket,
(WIDTH_BUCKET(price, 0, 500, 5) - 1) * 100 AS bucket_from
FROM products
ORDER BY price;
price_band | products | names
------------------+----------+-----------------------------------------------------------------------
1: under 25 | 1 | Merino socks
2: 25 to 99.99 | 4 | Basecamp lantern, Glow head torch, Day 18 backpack, Trail 30 backpack
3: 100 to 299.99 | 1 | Ridge 2 tent
4: 300 and over | 1 | Summit 4 tent
(4 rows)
name | price | bucket | bucket_from
-------------------+--------+--------+-------------
Merino socks | 16.00 | 1 | 0
Basecamp lantern | 27.00 | 1 | 0
Glow head torch | 34.50 | 1 | 0
Day 18 backpack | 54.00 | 1 | 0
Trail 30 backpack | 89.95 | 1 | 0
Ridge 2 tent | 249.99 | 3 | 200
Summit 4 tent | 489.00 | 5 | 400
(7 rows)
The CASE checks its WHEN clauses in order and uses the first that's true, so each condition only needs the upper limit: a price that reaches WHEN price < 100 is already known to be at least 25. Write the bands in increasing order, and make sure every value lands in exactly one band, with an ELSE for the last.
Two details make band reports tidy:
- Sort order. Band labels sort as text, so
'100 to 299.99'would come before'25 to 99.99'. The labels here start with a number to force the right order. Alternatively, also compute a band number and sort by it. - Empty bands. A band with no products doesn't appear at all. To show it with 0, left-join a list of all bands to the counts, the same technique as filling missing dates (article 41).
WIDTH_BUCKET(value, low, high, count) divides the range from low to high into count equal-width buckets and returns the bucket number, 1 to count. Values below low give 0, and values at or above high give count + 1. With 0 to 500 in 5 buckets, each is 100 wide. It's a quick way to build a histogram's x-axis. WIDTH_BUCKET exists in PostgreSQL and Oracle. Elsewhere, compute FLOOR((value - low) / width) + 1.
Equal-count buckets and histograms
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- One row per order line, with its category, order status and line amount
CREATE VIEW sales AS
SELECT o.order_id, o.placed_on, o.status, p.category, p.brand,
oi.qty, oi.qty * oi.unit_price AS amount
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
JOIN products p ON p.product_id = oi.product_id;
-- Equal-count buckets with NTILE: each group has (almost) the same number of rows
SELECT name, price,
NTILE(3) OVER (ORDER BY price) AS price_third
FROM products
ORDER BY price;
-- A text histogram: one # per order line, and a bar scaled to the largest value
SELECT category,
COUNT(*) AS lines,
repeat('#', COUNT(*)::int) AS bar,
SUM(amount) AS revenue,
repeat('=', ROUND(20 * SUM(amount) / MAX(SUM(amount)) OVER ())::int) AS revenue_bar
FROM sales
WHERE status <> 'cancelled'
GROUP BY category
ORDER BY revenue DESC;
name | price | price_third
-------------------+--------+-------------
Merino socks | 16.00 | 1
Basecamp lantern | 27.00 | 1
Glow head torch | 34.50 | 1
Day 18 backpack | 54.00 | 2
Trail 30 backpack | 89.95 | 2
Ridge 2 tent | 249.99 | 3
Summit 4 tent | 489.00 | 3
(7 rows)
category | lines | bar | revenue | revenue_bar
----------+-------+-----+---------+----------------------
tents | 2 | ## | 738.99 | ====================
lighting | 2 | ## | 103.50 | ===
clothing | 3 | ### | 94.00 | ===
packs | 1 | # | 89.95 | ==
(4 rows)
Equal-width buckets can be very uneven: five of the seven products fall in the first price bucket. NTILE(n) (article 27) does the opposite. It splits the rows, in order, into n groups with as equal a count as possible: the cheapest third, the middle third and the most expensive third. With 7 rows and 3 groups, the sizes are 3, 2 and 2, because the first groups get the extra rows. NTILE is how you split customers into quartiles or deciles by spending.
The second query draws a text histogram, useful in a terminal or a log: repeat('#', n) gives one character per order line. A bar proportional to revenue must be scaled, or a large value would produce thousands of characters: dividing each category's revenue by the largest, MAX(SUM(amount)) OVER (), and multiplying by 20 gives bars up to 20 characters long. The tents' bar dwarfs the rest, and the picture says so faster than the numbers.
Shares of a total
"What percentage of revenue comes from each category?" needs each group's value divided by the total over all groups. A window function over the aggregated rows provides that total in the same query:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- One row per order line, with its category, order status and line amount
CREATE VIEW sales AS
SELECT o.order_id, o.placed_on, o.status, p.category, p.brand,
oi.qty, oi.qty * oi.unit_price AS amount
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
JOIN products p ON p.product_id = oi.product_id;
-- Shares of a total: divide by a window SUM over the whole result
SELECT category,
SUM(amount) AS revenue,
ROUND(100 * SUM(amount) / SUM(SUM(amount)) OVER (), 1) AS pct_of_total
FROM sales
WHERE status <> 'cancelled'
GROUP BY category
ORDER BY revenue DESC;
-- Shares within a group: PARTITION BY the group
SELECT category, status, SUM(amount) AS revenue,
ROUND(100 * SUM(amount) / SUM(SUM(amount)) OVER (PARTITION BY category), 1) AS pct_of_category
FROM sales
WHERE category IN ('tents', 'lighting')
GROUP BY category, status
ORDER BY category, status;
category | revenue | pct_of_total
----------+---------+--------------
tents | 738.99 | 72.0
lighting | 103.50 | 10.1
clothing | 94.00 | 9.2
packs | 89.95 | 8.8
(4 rows)
category | status | revenue | pct_of_category
----------+-----------+---------+-----------------
lighting | delivered | 34.50 | 33.3
lighting | shipped | 69.00 | 66.7
tents | pending | 489.00 | 66.2
tents | shipped | 249.99 | 33.8
(4 rows)
SUM(SUM(amount)) OVER () looks odd but reads from the inside out: SUM(amount) is the group's revenue, from GROUP BY, and the outer SUM(...) OVER () adds those up over all the result's rows (article 26). Tents bring in 72% of revenue.
For shares within a group, partition the window: OVER (PARTITION BY category) divides each status's revenue by its own category's total, so the percentages add up to 100 within each category.
Two habits keep percentages correct:
- Multiply before dividing, and make sure the division isn't between integers.
100 * count / totalwith integer columns truncates, andcount / total * 100gives 0 for every share below 100%. Hereamountis a decimal. With counts, write100.0 * COUNT(*) / ...(article 38). - Round only for display, at the end. Rounded percentages may not add up to exactly 100, which is normal.
Running percentages and ABC analysis
A running percentage answers "which few items account for most of the total?", the Pareto principle, often summed up as 80% of sales coming from 20% of products. Inventory planners call the classification ABC analysis: class A items make up the first 80% of revenue and deserve the most attention.
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- Running percentage: which products make up 80% of revenue? (ABC analysis)
WITH product_revenue AS (
SELECT p.name, SUM(oi.qty * oi.unit_price) AS revenue
FROM order_items oi
JOIN orders o ON o.order_id = oi.order_id
JOIN products p ON p.product_id = oi.product_id
WHERE o.status <> 'cancelled'
GROUP BY p.name
)
SELECT name, revenue,
ROUND(100 * SUM(revenue) OVER (ORDER BY revenue DESC, name)
/ SUM(revenue) OVER (), 1) AS cumulative_pct,
CASE WHEN SUM(revenue) OVER (ORDER BY revenue DESC, name) - revenue
< 0.8 * SUM(revenue) OVER () THEN 'A'
ELSE 'B' END AS class
FROM product_revenue
ORDER BY revenue DESC, name;
name | revenue | cumulative_pct | class
-------------------+---------+----------------+-------
Summit 4 tent | 489.00 | 47.6 | A
Ridge 2 tent | 249.99 | 72.0 | A
Glow head torch | 103.50 | 82.1 | A
Merino socks | 94.00 | 91.2 | B
Trail 30 backpack | 89.95 | 100.0 | B
(5 rows)

SUM(revenue) OVER (ORDER BY revenue DESC, name)is a running total (article 28) from the largest product down. Dividing by the grand total gives the cumulative percentage. Thenamein theORDER BYbreaks ties, so products with equal revenue don't get the same running total.- The class is decided by the running total before each product,
running - revenue: a product is in class A if the products before it hadn't yet reached 80%. So the head torch, which takes the total from 72% to 82.1%, is still in A. Defining the class by the running total including the product would leave out the item that crosses the line, which is a choice, but should be made deliberately.
Three of the five products bring in 82% of the revenue. The Day 18 backpack doesn't appear, because its only order was cancelled.
Top N and "everything else"
Charts and summaries often show the top few categories and combine the rest into one "other" row, so the numbers still add up to the total:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- One row per order line, with its category, order status and line amount
CREATE VIEW sales AS
SELECT o.order_id, o.placed_on, o.status, p.category, p.brand,
oi.qty, oi.qty * oi.unit_price AS amount
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
JOIN products p ON p.product_id = oi.product_id;
-- The top 2 categories, with the rest combined into "other"
WITH ranked AS (
SELECT category, SUM(amount) AS revenue,
ROW_NUMBER() OVER (ORDER BY SUM(amount) DESC) AS rn
FROM sales
WHERE status <> 'cancelled'
GROUP BY category
)
SELECT CASE WHEN rn <= 2 THEN category ELSE 'other' END AS category,
SUM(revenue) AS revenue
FROM ranked
GROUP BY CASE WHEN rn <= 2 THEN category ELSE 'other' END
ORDER BY MIN(rn);
category | revenue
----------+---------
tents | 738.99
lighting | 103.50
other | 183.95
(3 rows)
The CTE ranks the categories by revenue, and the outer query groups again by a CASE that keeps the top two names and replaces the rest with 'other'. ORDER BY MIN(rn) keeps the ranking order, with "other" last because its smallest rank is 3. The three rows still add up to the full revenue, 1,026.44.
Use ROW_NUMBER for exactly N named rows, or RANK if tied categories should both be shown (article 27).
Subtotal reports
ROLLUP (article 20) adds subtotal and total rows. A finished report also needs readable labels and sensible ordering:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- One row per order line, with its category, order status and line amount
CREATE VIEW sales AS
SELECT o.order_id, o.placed_on, o.status, p.category, p.brand,
oi.qty, oi.qty * oi.unit_price AS amount
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
JOIN products p ON p.product_id = oi.product_id;
-- A report with subtotals and labels: ROLLUP, GROUPING and share of the grand total
WITH base AS (
SELECT category, status, amount
FROM sales
WHERE category IN ('tents', 'packs')
)
SELECT CASE WHEN GROUPING(category) = 1 THEN 'All categories' ELSE category END AS category,
CASE WHEN GROUPING(category) = 1 THEN ''
WHEN GROUPING(status) = 1 THEN 'subtotal'
ELSE status END AS status,
COUNT(*) AS lines,
SUM(amount) AS revenue,
ROUND(100 * SUM(amount) / (SELECT SUM(amount) FROM base), 1) AS pct
FROM base
GROUP BY ROLLUP (category, status)
ORDER BY GROUPING(category), category, GROUPING(status), status;
category | status | lines | revenue | pct
----------------+-----------+-------+---------+-------
packs | cancelled | 1 | 54.00 | 6.1
packs | delivered | 1 | 89.95 | 10.2
packs | subtotal | 2 | 143.95 | 16.3
tents | pending | 1 | 489.00 | 55.4
tents | shipped | 1 | 249.99 | 28.3
tents | subtotal | 2 | 738.99 | 83.7
All categories | | 4 | 882.94 | 100.0
(7 rows)
GROUPING(col)returns 1 when a row is a subtotal overcol, that is, when the NULL incolwas produced byROLLUPrather than coming from the data. TheCASEexpressions turn those NULLs into'subtotal'and'All categories'.- Ordering by
GROUPING(category), category, GROUPING(status), statusputs each category's detail rows first, its subtotal after them, and the grand total at the very end. - The percentage column divides by the grand total, computed once from the same filtered rows in the CTE. Each category's subtotal shows its share, and the detail rows within a category add up to it.
Showing a label only once
Printed reports often show a group's name only on its first row, leaving it blank below:
-- Show each category only on its first row, as printed reports often do
CREATE TABLE stock_list (category TEXT, product TEXT, stock INTEGER);
INSERT INTO stock_list VALUES
('lighting', 'Basecamp lantern', 15), ('lighting', 'Glow head torch', 40),
('packs', 'Day 18 backpack', 0), ('packs', 'Trail 30 backpack', 22),
('tents', 'Ridge 2 tent', 12), ('tents', 'Summit 4 tent', 3);
SELECT CASE WHEN ROW_NUMBER() OVER (PARTITION BY category ORDER BY product) = 1
THEN category END AS category,
product, stock
FROM stock_list
ORDER BY stock_list.category, product;
category | product | stock
----------+-------------------+-------
lighting | Basecamp lantern | 15
| Glow head torch | 40
packs | Day 18 backpack | 0
| Trail 30 backpack | 22
tents | Ridge 2 tent | 12
| Summit 4 tent | 3
(6 rows)
ROW_NUMBER() within each category finds the first row, and the CASE keeps the name only there. The outer ORDER BY must match the window's order, or the label can end up on a row that isn't first. This is display formatting, so when a reporting tool or the application can do it, let it: the blank values are no longer real data, and the rows can't be sorted or filtered by category afterwards.
What's current
WIDTH_BUCKETis standard SQL, supported by PostgreSQL and Oracle. PostgreSQL also has a form (since 9.5) that takes a sorted array of bucket boundaries, for buckets of different widths.- SQL Server 2022's
DATE_BUCKETgroups dates into fixed-size periods, a date version of equal-width buckets. GROUPING SETS,ROLLUPandCUBEare supported by PostgreSQL, SQL Server, Oracle and MySQL 8 (WITH ROLLUPonly). SQLite has none of them: useUNION ALLof separate groupings.
Common questions
How do I put values into ranges?
With a CASE expression of increasing upper limits, then GROUP BY the result. WIDTH_BUCKET gives equal-width ranges, and NTILE equal-count groups.
How do I calculate a percentage of the total?
100.0 * SUM(x) / SUM(SUM(x)) OVER () in a grouped query. Partition the window for percentages within a group.
Why are all my percentages 0?
Integer division: count / total is 0 when count < total. Multiply by 100.0 first, or cast to a decimal.
How do I show the top 5 and group the rest as "other"?
Rank the groups in a CTE, then group again by CASE WHEN rank <= 5 THEN name ELSE 'other' END.
How do I label ROLLUP subtotal rows?
Test GROUPING(col) = 1 in a CASE and return a label. Don't test col IS NULL, which would also match real NULLs in the data.
Summary
- Map values to bands with an ordered
CASE, and group by the band. Mind the label sort order and empty bands. WIDTH_BUCKETmakes equal-width buckets.NTILEmakes equal-count groups.repeatwith a scaled count draws a text histogram.SUM(SUM(x)) OVER ()gives the grand total in a grouped query, andPARTITION BYgives group totals for shares within groups.- A running
SUM ... OVER (ORDER BY ...)divided by the total gives a cumulative percentage, the basis of ABC analysis. - Rank, then regroup with a
CASE, to show the top N plus "other". ROLLUPwithGROUPINGand careful ordering produces labelled subtotal reports.
Practice questions
Write a query that counts products in the stock bands "out of stock" (0), "low" (1 to 10) and "in stock" (more than 10).
Answer
SELECT CASE WHEN stock = 0 THEN '1: out of stock'
WHEN stock <= 10 THEN '2: low'
ELSE '3: in stock'
END AS stock_band,
COUNT(*) AS products
FROM products
GROUP BY stock_band
ORDER BY stock_band;
out of stock 1 (Day 18 backpack), low 1 (Summit 4 tent, 3 in stock), in stock 5.
What does WIDTH_BUCKET(500, 0, 500, 5) return, and why?
Answer
- The upper bound is exclusive: buckets 1 to 5 cover 0 up to, but not including, 500, and values at or above it go to bucket
count + 1.
In SQL Server, this query returns 0 for every category's share. Why, and how do you fix it?
SELECT category, COUNT(*) / SUM(COUNT(*)) OVER () * 100 AS pct
FROM sales GROUP BY category;
Answer
In SQL Server, COUNT(*) and the SUM of it are both integers, so the division truncates to 0 before the multiplication. Multiply first, by a decimal: 100.0 * COUNT(*) / SUM(COUNT(*)) OVER (). PostgreSQL happens to return the right answer here, because its SUM of a bigint is a numeric, but the fixed version is correct everywhere.
In the ABC query, why does the ORDER BY of the running total include name?
Answer
With ORDER BY revenue DESC alone, products with equal revenue are peers, and the default RANGE frame gives them all the same running total, which includes all of them (article 28). Adding a unique tiebreaker makes the running total grow one product at a time.
Previous: Unpivoting in SQL: Turning Columns Into Rows
Next: Advanced Searching in SQL: Top-N, Extremes, Skipping Rows and Previous Values

More in SQL Course
Quiz: SQL Dialect Differences (PostgreSQL, MySQL, SQL Server, Oracle, SQLite)
Twenty-four questions on how the major SQL databases differ: limiting rows, concatenation, empty strings, identifier case, upserts, identity columns, transactional DDL, error handling, isolation defaults, booleans, set operations, RETURNING, dates and typing.
Quiz: SQL Delicate Details
Twenty-five questions on SQL's subtle corners: NULLs in aggregates, IN and CHECK, sort order of NULLs, rounding, CHAR padding, window frame defaults, identity gaps, LIKE escapes, empty groups, set operations and multi-column updates.
Quiz: SQL Interview Questions
Thirty SQL questions of the kind asked in developer and analyst interviews: WHERE vs HAVING, DELETE vs TRUNCATE, keys, joins, duplicates, Nth-highest values, window functions, ACID, isolation, locking, indexes, views, procedures and performance.
Quiz: SQL Course Final Exam (All 15 Parts)
The final exam for the SQL course: thirty questions across all fifteen parts, from query processing, NULLs, joins and aggregation through windows, data changes, types, design, indexes, security, transactions, procedural SQL and tuning.
Discussion
Sign in to ask a question or share what you learned.