I am struggling with creating an SQL query using aggregates using PostgreSQL. Consider the following tables:
CREATE TABLE thing (
id INT NOT NULL PRIMARY KEY,
price NUMERIC(10,2) NOT NULL,
description VARCHAR(255) NOT NULL,
url VARCHAR(255) NOT NULL,
location_id INT NOT NULL REFERENCES location(id)
)
CREATE TABLE location (
id INT NOT NULL PRIMARY KEY,
type INT NOT NULL,
name VARCHAR(255) NOT NULL
)
Now I would like to get all the record entries for each location using location.type = xxx, which have the lowest price.
Sort of:
SELECT min(price) FROM thing
INNER JOIN location ON (thing.location_id = location.id)
WHERE type = xxx
GROUP BY location_id
This will tell me the lowest price for each xxx type location, but how can I get the rows (or their primary keys) of these columns from the table?
source
share