Calculating a percentage for a group

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, 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?


    Requires Free Membership to View

    By submitting your registration information to SearchOracle.com you agree to receive email communications from TechTarget and TechTarget partners. We encourage you to read our Privacy Policy which contains important disclosures about how we collect and use your registration and other information. If you reside outside of the United States, by submitting this registration information you consent to having your personal data transferred to and processed in the United States. Your use of SearchOracle.com is governed by our Terms of Use. You may contact us at webmaster@TechTarget.com.

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


This was first published in July 2003

Join the conversationComment

Share
Comments

    Results

    Contribute to the conversation

    All fields are required. Comments will appear at the bottom of the article.