In PostgreSQL: I have a Table that has 3 columns:
CustomerNum, OrderNum, OrderDate
.
There may(or may not) be many orders for each customer per date range. What I am needing is the last OrderNum for each Customer that lies in the date range that is supplied. What I have been doing is getting a ResultSet of the customers and querying each one separately, but this is taking too much time.
Is there any way of using a sub-select to select out the customers, then get the last OrderNum for each Customer?
If by last order number you mean the largest order number then you can just use your select as the predicate for customer num, group the results and select the maximum:
If the last order number isn't necessarily the largest order number then you'll need to either find the largest order date for each customer and join it together with the rest of the orders to find the corresponding number(s):
result:
On postgres you can also use the non-standard
DISTINCT ON
clause:See http://www.postgresql.org/docs/current/static/sql-select.html#SQL-DISTINCT
that's all.
Not sure about your Customer table's structure or relationships, but this should work: