Calculating a percentage for a group
I have Member table with a Nationality column, and I want to get the percentage breakdown of members by Nationality,...
Continue Reading This Article
Enjoy this article as well as all of our content, including E-Guides, news, tips and more.
for example:
- American 29%
- Canadian 14%
- Mexican 11%
- ...
Is there an efficient way to do this in a single query? If I were to do this:
SELECT nationality, ((COUNT(*) * 100)/(select count(*) from member)) as percentage FROM member GROUP BY nationality ORDER BY nationality;
Wouldn't this repeatedly execute the inner query over and over?
That's a very good question, and shows you're thinking. No, the database optimizer is smart enough to recognize that select count(*) from member is independent of the outer query, and will execute it only once, before the outer query. Then it will just use the result in the calculation of the percentage for each group.
As far as I can tell, your query will give you exactly the results you require, and efficiently to boot.
Good job.
For More Information
- Dozens more answers to tough SQL questions from Rudy Limeback.
- The Best SQL Web Links: tips, tutorials, scripts, and more.
- Have an SQL tip to offer your fellow DBAs and developers? The best tips submitted will receive a cool prize. Submit your tip today!
- Ask your technical SQL questions -- or help out your peers by answering them -- in our live discussion forums.
- Ask the Experts yourself: Our SQL, database design, SQL Server, DB2, metadata, object-oriented and data warehousing gurus are waiting to answer your toughest questions.