Skip to content
Advertisement

Calculate the return rate per customer based on the last three orders

DB-Fiddle

Expected Result:


In the table above I have orders per customer and their corresponding sales_volume and return_volume.

Now, I want to calculate the return_rate of the last 3 orders per customer.

So far, I came up with this query:

But I have no clue how I can apply the limit to the calculation of the return_rate per customer.
How do I have to modify the query to achieve the expected results?

Advertisement

Answer

If I understand correctly, you can use ROW_NUMBER() to enumerate the rows and then filter before aggregating:

Here is a db<>fiddle.

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