I'm working on a Web-based poll where, among other things, you fill in your gender (m,f). I would like to construct an SQL query that calculates the fractions of males and females in my table. The following returns the absolute number of people of each gender but having it in fractions is something I don't know how to do.
SELECT gender, Count(*) AS Number FROM mytable GROUP BY gender;
Requires Free Membership to View
The fractions that you seek can only be calculated if you know the total number of people in the table. The following query will produce the correct results:
select gender
, count(*) as number
, count(*)
/ ( select count(*)
from mytable ) as fraction
from mytable
group
by gender
The subquery that acts as the divisor gets the overall count for the entire table. Furthermore, it is not correlated. This means that the database engine can run it separately ahead of time, before tackling the main query. Then, no matter how many groups are in the main query, the number obtained by the subquery can be used in the calculation of each fraction.
Note that in this type of construction, the subquery to get the overall count is a scalar subquery. Used in the SELECT list, a subquery is permitted to return only one value.
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, Oracle, SQL Server, DB2, metadata, object-oriented and data warehousing gurus are waiting to answer your toughest questions.
This was first published in February 2003
Join the conversationComment
Share
Comments
Results
Contribute to the conversation