I have a SQL Server table that contains users & their grades. For simplicity's sake, lets just say there are 2 columns - name
& grade
. So a typical row would be Name: "John Doe", Grade:"A".
I'm looking for one SQL statement that will find the percentages of all possible answers. (A, B, C, etc...) Also, is there a way to do this without defining all possible answers (open text field - users could enter 'pass/fail', 'none', etc...)
The final output I'm looking for is A: 5%, B: 15%, C: 40%, etc...
I simply use this when ever I need to work out a percentage..
Note that 100.0 returns decimals, whereas 100 on it's own will round up the result to the nearest whole number, even with the ROUND() function!
You have to calculate the total of grades If it is SQL 2005 you can use CTE
The following should work
EDIT: Moved the
* 100
and added the1.0
to ensure that it doesn't do integer divisionYou can use a subselect in your from query (untested and not sure which is faster):
Or
Or
You can also use a stored procedure (apologies for the Firebird syntax):
Instead of using a separate CTE to get the total, you can use a window function without the "partition by" clause.
If you are using:
to get the count for a group, you can use:
to get the total count.
For example:
It tends to be faster in my experience, but I think it might internally use a temp table in some cases (I've seen "Worktable" when running with "set statistics io on").
EDIT: I'm not sure if my example query is what you are looking for, I was just illustrating how the windowing functions work.
In any sql server version you could use a variable for the total of all grades like this: