Skip to content
Advertisement

How to select TOP records in Postgres. Not a similar question

I have a table with three columns (City, Orderid, Total_quantity) and more than 500 rows. I want to fetch the top 50 records according to total_quantity wise. I can do this with rank_number but the twist can be understood with an example.

Example: Select top 5 (only for example) considering there are only 3 cities.

If I select the top 5 then the first record should be from city A with max total Quantity, the second record should be from city B with max total quantity, the third record should be from city C with max quantity. Here is the twist, the fourth record should be from city A with max quantity and then the final fifth record should be from city B with max total quantity. So the output will be like

Output:

Advertisement

Answer

Let me know if it works

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