Q

Percentages of overall total

I have a Bookings table with a character field called Status, which contains the values ATTEN and NOATT. I need the percentage of NOATT. I've tried but I can't get it to work.

I have a Bookings table with a character field called Status, which contains the values ATTEN and NOATT. I can count(status) and group and get the following results.

ATTEN 11
NOATT  9

I need the percentage of NOATT. I've tried the following but I can't get it to work.

select count(bookings.status) from bookings 
where bookings.status = 'NOATT'
/ (select count(bookings.status) from bookings

Any help would be greatly appreciated.

You were on the right track, but the syntax was not quite right. Here's what you need:

select 100.0 * count(bookings.status) 
       / ( select count(bookings.status) 
             from bookings )
  from bookings 
 where bookings.status = 'NOATT'

The subquery used as the divisor is a scalar subquery. That means it returns a single value (one column, one row). Any subquery used in the SELECT list must be a scalar subquery.

To get the percentages of all statuses, use this:

select bookings.status
     , 100.0 * count(bookings.status) 
       / ( select count(bookings.status) 
             from bookings )
  from bookings 
group
    by bookings.status

This produces one row per status, each with its percentage of the total. Note that the database optimizer can resolve the scalar subquery before executing the outer query. This means it does not actually execute the subquery for each status, just once overall.

This was first published in December 2005

Dig deeper on Oracle and SQL

Pro+

Features

Enjoy the benefits of Pro+ membership, learn more and join.

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.

0 comments

Oldest 

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to:

-ADS BY GOOGLE

SearchDataManagement

SearchBusinessAnalytics

SearchSAP

SearchSQLServer

TheServerSide

SearchDataCenter

SearchContentManagement

SearchFinancialApplications

Close