Skip to content
Advertisement

How to write this SQL query more elegantly ( joining + max query )

Ok I am using the following example from w3school

https://www.w3schools.com/sql/trysql.asp?filename=trysql_select_all

and I want to get the date in which the amount was ordered

This works but my guts tell me I need to use joining or having ??

Advertisement

Answer

You want the date of the order that has the maximum quantity.

It does not look like you do need two levels of subqueries. You could use a row-limiting subquery instead:

This is shorter, and does not fail if there is more than one order with the same, maximum quantity (while your original code does, because the subquery returns more than one row).

Another approach uses window functions:

This will properly handle top ties, in the sense that it will return them all (while the first query returns only one of them).

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