Skip to content
Advertisement

SQL perform AVG after MAX

I have two tables. Table1:

and Table2:

I am trying to Join Table1 to Table2 while filtering the outputs so only one row where date is at its maximum for those classifications are displayed and the average cost at that maximum date is also displayed. Here is my current code:

With the example data given above, my result looks like this:

When it should just be looking like this

The average cost is including values where date is not at its maximum. I’m assuming this is due to AVG(cost) being executed before Table2 is filtered with MAX(Date). Here’s what I’ve tried:

and

The first gives no results and the second results in an error, ORA-01427: single-row subquery returns more than one row. The rest of what I’ve tried is basically variations of the above, but I’m still not getting the results expected. I’m not sure how to make the AVG function perform only where Date is at its max…

Advertisement

Answer

Your definition of t2 looks like this:

Instead, to compute the average only over the most recent date, it should use a different aggregate function – the LAST function, like so:

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