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.

    Requires Free Membership to View

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

There are Comments. Add yours.

 
TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
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
Sort by: OldestNewest

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: