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