With a table with data like this:
a a a b b cHow can I show these results as a percentage (i.e count a / total records):
a 50 b 33.333 c 16.666I know a GROUP BY must be there. I want to do this in one query.
I'll try to reproduce your scenario. Here's the SQL to create and populate the table:
create table MyTable ( MyColumn char(1) ); insert into MyTable values ('a'); insert into MyTable values ('a'); insert into MyTable values ('a'); insert into MyTable values ('b'); insert into MyTable values ('b'); insert into MyTable values ('c');I came up with two different yet similar solutions. The first involves using a scalar subquery in the SELECT clause to obtain the total count. Here's the SQL:
select MyColumn, round( 100.0 * count(*) / ( select count(*) from MyTable ) ,3 ) Perc from MyTable group by MyColumn;The second solution involves a cross join with the same subquery. Because cross joins are the SQL equivalent to multiplication, and we know that the subquery returns one and only one row, then we know that the cross join will return one row per row in MyTable. Mathematically, this is the equivalent of saying, "X multiplied by 1 equals X." Grouping by T.CNT is required in order to make the join work, but this doesn't change the outcome because we know that T.CNT is constant for the entire query. And we know that having a secondary sort by a constant won't affect order.
select MyColumn, round(100.0 * count(*) / t.cnt,3) Perc from MyTable cross join ( select count(*) cnt from MyTable ) t group by MyColumn, t.cnt;Both queries give the same result set:
MYCOLUMN PERC -------- ---------- a 50 b 33.333 c 16.667Which query you choose to use might depend on your particular SQL vendor's implementation, performance and/or which one you like better.
For More Information
- What do you think about this answer? E-mail the edtiors at editor@searchDatabase.com with your feedback.
- 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 March 2002