Q
Problem solve Get help with specific problems with your technologies, process and projects.

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?


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 last published in July 2003

Dig Deeper on Oracle and SQL

PRO+

Content

Find more PRO+ content and other member only offers, here.

Have a question for an expert?

Please add a title for your question

Get answers from a TechTarget expert on whatever's puzzling you.

You will be able to add details on the next page.

Start the conversation

Send me notifications when other members comment.

By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Please create a username to comment.

-ADS BY GOOGLE

SearchDataManagement

SearchBusinessAnalytics

SearchSAP

SearchSQLServer

TheServerSide.com

SearchDataCenter

SearchContentManagement

SearchFinancialApplications

Close