Skip to content
Advertisement

Find Nth value and average value corresponding to each group in SQL

I have a table with name and grades for some users

I want an output table grouped by the name, along with the average grade and the nth lowest value for each name.

I tried to use window function nth_value() but I get an error when I try to execute the query (n = 2 here)

Error(s), warning(s):

42803: column “grades.grade” must appear in the GROUP BY clause or be used in an aggregate function

What is the correct way of writing such a query?

Advertisement

Answer

Starting from your current attempt, a simple option uses a window average and distinct:

Alternatively, you can rank grades in a subquery, and use conditional aggregation in the outer query:

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement