Skip to content
Advertisement

How can I get last 2 records from another table as columns

I have a table called products with this schema:

And another table with fee change log with this schema:

Is there anyway to get last 2 fee changes for each sku in one sql and not 2 rows for each sku, I want to have 2 new columns with old_fee_1, new _fee_1, old_fee_2, new_fee_2:

Desired result:

dbfiddle

Advertisement

Answer

As starting point I took your query from the fiddle you linked:


demo: db<>fiddle

You can use the FILTER clause (alternatively it works with a CASE WHEN construct as well) to pivot your joined table. To get the pivot value, you can add a row count (using the row_number() window function):

  1. Create pivot value
  2. Do the filtered aggregation to create the pivoted table.
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement