Ok, I’m stuck on an SQL query and tried long enough that it’s time to ask for help :) I'm using Objection.js – but that's not super relevant as I really just can't figure out how to structure the SQL.
I have the following example data set:
Items
id | name |
---|---|
1 | Test 1 |
2 | Test 2 |
3 | Test 3 |
Listings
id | item_id | price | created_at |
---|---|---|---|
1 | 1 | 100 | 1654640000 |
2 | 1 | 60 | 1654640001 |
3 | 1 | 80 | 1654640002 |
4 | 2 | 90 | 1654640003 |
5 | 2 | 90 | 1654640004 |
6 | 3 | 50 | 1654640005 |
What I’m trying to do:
- Return the lowest priced listing for each item
- If all listings for an item have the same price, I want to return the newest of the two items
- Overall, I want to return the resulting items by price
I’m trying to write a query that returns the data:
id | item_id | name | price | created_at |
---|---|---|---|---|
6 | 3 | Test 3 | 50 | 1654640005 |
2 | 1 | Test 1 | 60 | 1654640001 |
5 | 2 | Test 2 | 90 | 1654640004 |
Any help would be greatly appreciated! I'm also starting fresh, so I can add new columns to the data if that would help at all :)
An example of where my query is right now:
select * from "listings" inner join (select "item_id", MIN(price) as "min_price" from "listings" group by "item_id") as "grouped_listings" on "listings"."item_id" = "grouped_listings"."item_id" and "listings"."price" = "grouped_listings"."min_price" where "listings"."sold_at" is null and "listings"."expires_at" > ? order by CAST(price AS DECIMAL) ASC limit ?;
This gets me listings – but if two listings have the same price, it returns multiple listings with the same item_id – not ideal.