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.
Dig Deeper on Oracle and SQL
Related Q&A from Rudy Limeback
Read an example of an SQL case expression from our SQL expert Rudy Limeback.continue reading
Read about the Mimer Validator, a tool used to verify your SQL code, in this tip from SQL expert Rudy Limeback.continue reading
Read SQL expert Rudy Limeback's advice for counting combinations in a table with SQL's GROUP BY clausecontinue reading
Have a question for an expert?
Please add a title for your question
Get answers from a TechTarget expert on whatever's puzzling you.