Say I have a table ‘orders’ created as:
CREATE TABLE orders (id SERIAL, customerID INTEGER, timestamp BIGINT, PRIMARY KEY(id));
Timestamp being the UNIX timestamp. Now i want to select the ids of the LATEST orders for every customer. As a view would be nice.
however the following statement
CREATE VIEW lastOrders AS SELECT id, customerID, MAX(timestamp) FROM orders GROUP BY customerID;
Causes a postgre error:
ERROR: column ‘orders.id’ must appear in the GROUP BY clause or be used in an aggregate function
What am I doing wrong?
For these kind of things you can use 2 approaches. One has been already shown by Jens.
Other, is to use ‘DISTINCT ON’ clause: