Skip to content
Advertisement

Select pairs of values based on condition in other column – PostgreSQL

I’ve been trying to solve an issue for the past couple of days, but couldn’t figure out what the solution would be…

I have a table as the following:

And I woud like to select pairs of shop IDs for which the price of the same article is higher. F.e. this should look like:

… showing that Article 2 ist more expensive in ShopID 4 than in ShopID 2. Etc

My code so far looks as following:

But it doesn’t give the result I am searching for.

Can anyone help me with this objective? Thank you very much.

Advertisement

Answer

The problem here is about calculating Top N items per Group.

Assuming you have the following data, in table sales.

With the following query we can create a partition for each ArticleId

This will result:

Then we simply select Top 2 items for each AritcleId:

which will result:

Finally, we can use crosstab function to get the expected pivot view.

And the result:

Note: You may need to call CREATE EXTENSION tablefunc; in case if you get the error function crosstab(unknown) does not exist.

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