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...
The most efficient (using over()).
Universal (any SQL version).
With CTE, the least efficient.
You need to group on the grade field. This query should give you what your looking for in pretty much any database.
You should specify the system you're using.
I have tested the following and this does work. The answer by gordyii was close but had the multiplication of 100 in the wrong place and had some missing parenthesis.
This is, I believe, a general solution, though I tested it using IBM Informix Dynamic Server 11.50.FC3. The following query:
gives the following output on the test data shown below the horizontal rule. The
ROUND
function may be DBMS-specific, but the rest (probably) is not. (Note that I changed 100 to 100.0 to ensure that the calculation occurs using non-integer - DECIMAL, NUMERIC - arithmetic; see the comments, and thanks to Thunder.)