I have the following 2 tables:
orders
id | user | amount |
1 | ALEX | 10 |
2 | BARB | 20 |
3 | CARL | 30 |
4 | DAVE | 40 |
5 | EVIE | 50 |
6 | FRAN | 60 |
history
order_id | status | date |
1 | pending | 2017-04-01 10:02:47 |
1 | shipped | 2017-05-01 05:58:35 |
1 | delivered | 2017-06-01 12:56:32 |
2 | pending | 2017-04-01 11:44:03 |
2 | shipped | 2017-05-01 14:51:49 |
2 | delivered | 2017-06-01 23:27:16 |
3 | pending | 2017-07-01 20:44:02 |
3 | shipped | 2017-08-01 17:10:18 |
4 | pending | 2017-07-01 11:19:15 |
4 | shipped | 2017-08-01 15:17:25 |
5 | pending | 2017-10-01 21:59:13 |
6 | pending | 2017-10-01 02:47:33 |
These are the important fields, as each table has a couple more columns that are not needed nor useful. What I need is a query that will show me only the latest "status" and "date" for each "order_id", meaning there should only be 1 line per "order_id". End result should look like so:
order_id | amount | user | status | date |
1 | 10 | ALEX | delivered | 2017-06-01 12:56:32 |
2 | 20 | BARB | delivered | 2017-06-01 23:27:16 |
3 | 30 | CARL | shipped | 2017-08-01 17:10:18 |
4 | 40 | DAVE | shipped | 2017-08-01 15:17:25 |
5 | 50 | EVIE | pending | 2017-10-01 21:59:13 |
6 | 60 | FRAN | pending | 2017-10-01 02:47:33 |
This is as far as I could go, which shows everything pretty much correctly but only for the delivered ones
SELECT orders.id, orders.user, orders.amount, history.status, history.date
FROM orders
JOIN history
ON history.order_id = orders.id
AND history.status = 'delivered'
ORDER BY history.date DESC
As far as the DBMS I'm using, I'm not entirely sure, I'm using the SQL editor on the Mode Analytics website. For some other issues I have used solutions that were apparently only valid for use in MySQL, but in some others I used some that were only valid for use with PostgreSQL.