SQL Shares, Rankings and Joined Text
What you will learn
- How to show each group as a share of the total
- How to rank groups with
ORDER BYandLIMIT - How to join the values of a group into one text with
GROUP_CONCAT - A checklist for a summary query you can trust
This lesson runs on the sample database you chose in lesson 1.1 (use the Example data picker at the top). Edit any query and press Run. Reset data puts the original rows back.
1. A group as a share of the total
A total per group is useful; the share of the whole is often more useful. Divide each group's value by the grand total. The grand total comes from a small query in brackets (a subquery, chapter 7), and 100.0 keeps the decimals (lesson 1.3):
Each payment method's share of the money received:
SELECT method, ROUND(SUM(amount), 2) AS total,
ROUND(100.0 * SUM(amount) / (SELECT SUM(amount) FROM payments), 1) AS share_percent
FROM payments GROUP BY method ORDER BY total DESC;
method total share_percent
-------- --------- -------------
card 126798.77 54.3
transfer 49583.35 21.3
wallet 30599.8 13.1
cash 26346.97 11.3
(4 rows)
Each kind's share of the ledger rows:
SELECT kind, COUNT(*) AS rows_found,
ROUND(100.0 * COUNT(*) / (SELECT COUNT(*) FROM transactions), 1) AS share_percent
FROM transactions GROUP BY kind ORDER BY rows_found DESC, kind;
kind rows_found share_percent
------------ ---------- -------------
deposit 3107 41.9
withdrawal 2519 34.0
transfer_in 539 7.3
transfer_out 539 7.3
fee 403 5.4
interest 308 4.2
(6 rows)
Each year's share of all students:
SELECT enrolled_year, COUNT(*) AS students,
ROUND(100.0 * COUNT(*) / (SELECT COUNT(*) FROM students), 1) AS share_percent
FROM students GROUP BY enrolled_year ORDER BY enrolled_year;
enrolled_year students share_percent
------------- -------- -------------
2023 83 23.1
2024 102 28.3
2025 86 23.9
2026 89 24.7
(4 rows)
The shares should add up to about 100 (rounding can leave a small difference). That is a quick check that the query is right.
2. Rankings: top groups
Sort the groups by the measure and keep the first few: "the top three". Add a tie-break so the order is stable (lesson 2.6):
The three countries with the most customers:
SELECT country, COUNT(*) AS customers FROM customers
GROUP BY country ORDER BY customers DESC, country LIMIT 3;
country customers
-------------- ---------
United Kingdom 35
Turkey 32
Brazil 30
(3 rows)
The three cities with the most customers:
SELECT city, COUNT(*) AS customers FROM customers
GROUP BY city ORDER BY customers DESC, city LIMIT 3;
city customers
----- ---------
Lima 25
Osaka 24
Hanoi 23
(3 rows)
The three busiest sections by number of enrollments:
SELECT section_id, COUNT(*) AS enrolled FROM enrollments
GROUP BY section_id ORDER BY enrolled DESC, section_id LIMIT 3;
section_id enrolled
---------- --------
31 34
34 34
33 33
(3 rows)
3. GROUP_CONCAT: the values of a group in one text
GROUP_CONCAT(x, separator) joins the values of a group into one text. It is useful for a short list next to a count:
The methods used each year, in one cell:
SELECT STRFTIME('%Y', paid_on) AS year, GROUP_CONCAT(DISTINCT method) AS methods_used
FROM payments GROUP BY STRFTIME('%Y', paid_on) ORDER BY year LIMIT 4;
year methods_used
---- -------------------------
2024 wallet,card,transfer,cash
2025 card,wallet,cash,transfer
2026 transfer,card,wallet,cash
(3 rows)
The account types and statuses seen in each branch, collected into one text:
SELECT branch_id, COUNT(*) AS accounts, GROUP_CONCAT(DISTINCT account_type) AS types
FROM accounts GROUP BY branch_id ORDER BY branch_id;
branch_id accounts types
--------- -------- ----------------
1 87 checking,savings
2 79 savings,checking
3 64 checking,savings
4 69 savings,checking
5 76 savings,checking
6 75 checking,savings
(6 rows)
The terms in which each course is taught:
SELECT course_id, COUNT(*) AS sections, GROUP_CONCAT(DISTINCT term) AS terms
FROM sections GROUP BY course_id ORDER BY course_id LIMIT 5;
course_id sections terms
--------- -------- -----------------------------------
1 1 2025-Autumn
2 3 2025-Spring,2025-Autumn,2026-Spring
3 2 2025-Spring,2025-Autumn
4 1 2025-Spring
5 2 2025-Spring,2025-Autumn
(5 rows)
In other databases. The function has other names elsewhere (for example
STRING_AGGin PostgreSQL,GROUP_CONCATin MySQL). The order of the joined values is not guaranteed unless the database lets you ask for one. Check the documentation of the database you use.
4. A checklist for a summary query
Before you trust a summary, check:
- What does one row of the result mean? (one country, one month...)
- Is every
SELECTcolumn grouped or aggregated? (lesson 3.2) - Is
WHEREdoing the row filtering andHAVINGthe group filtering? (lesson 3.3) - Do the parts add up to the total, or the shares to 100? (lessons 3.4 and 3.8)
- Did
NULLs change the numbers? (lesson 3.6) - Are decimals rounded only at the end? (lesson 1.6)
- Is the order stable, with a tie-break column? (lesson 2.6)
Worked example: the best customers
"Which three customers spent the most, and what share of all sales is that?"
| Step | Query part |
|---|---|
| total per customer | GROUP BY customer_id, SUM(amount) |
| biggest first, three only | ORDER BY total DESC, customer_id LIMIT 3 |
| share of all sales | 100.0 * SUM(amount) / (SELECT SUM(amount) FROM sales) |
| check | the three shares added to the others make 100 |
The same four ideas (group, sort, limit, divide by the total) solve most "top" questions. The table is made up.
Common mistakes
- Dividing by the wrong total, for example a total that already has a
WHEREthe groups do not. - Integer division in a share. Use
100.0 *. - A ranking without a tie-break.
- Relying on the order inside
GROUP_CONCAT.
Key takeaways
- A share is
100.0 * group_value / total; the total can be a subquery. - A top list is
GROUP BY,ORDER BYthe measureDESC(with a tie-break) andLIMIT. GROUP_CONCATcollects a group's values into one text; its name differs by database.- Check that parts add up and shares sum to 100.
Practice
1. Write the expression for a group's share of the total, as a percentage with one decimal.
Show answer
ROUND(100.0 * SUM(x) / (SELECT SUM(x) FROM t), 1) with the real column and table.
2. How do you get the five groups with the highest total?
Show answer
GROUP BY the group column, ORDER BY SUM(x) DESC (plus a tie-break) and LIMIT 5.
3. What does GROUP_CONCAT(name) return for a group?
Show answer
One text that joins the names of the group's rows, separated by commas.
4. Why should the shares add up to about 100?
Show answer
Each share is a part of the same total, so together they make the whole (rounding can leave a small difference).
5. Why write 100.0 * and not 100 *?
Show answer
With whole numbers the division would drop the decimals; 100.0 keeps them.
6. Name two items on the checklist for a summary query.
Show answer
For example: every SELECT column is grouped or aggregated, and the parts add up to the total.