Search code examples
sqlselectsumpercentage

how to reference an expression from the previous list value in sql?


So I'm not sure if I explained my question correctly in the title but I'll try saying it here. Let's say you have a table like this

enter image description here

How can you, in a single query, add up the grades and create a new column showcasing each row's percent of total grades like this:

enter image description here

I've tried doing something like

Select SUM( Grade) As total, Grade/total as Percent total

but it doesn't seem to work this way. I know I can obviously do two queries one for the sum and then make it happen directly. Can anyone tell help me do the percent total in a single query?


Solution

  • You can use a window function. For example:

    select *, 100 * grade / sum(grade) over() as percent_total from t