I'm a SQL newbie, here is my Table:
+----+--------+---------+------------+
| ID | Person | Success | Message |
+----+--------+---------+------------+
| 1 | Alice | 1 | Hello |
+----+--------+---------+------------+
| 2 | Bob | 0 | World |
+----+--------+---------+------------+
| 3 | Alice | 0 | Foo |
+----+--------+---------+------------+
| 4 | Clark | 1 | Bar |
+----+--------+---------+------------+
And I want to select latest (MAX ID assuming ID is incremental) records which is success for each person
Expected result:
+----+--------+---------+------------+
| ID | Person | Success | Message |
+----+--------+---------+------------+
| 4 | Clark | 1 | Bar |
+----+--------+---------+------------+
// Alice's latest record is not success, ignore
// Bob has no success record, ignore
Here is my current approach:
SELECT *
FROM test AS t1
RIGHT JOIN (
SELECT MAX(id) AS max_id
FROM test
GROUP BY Person
) AS t2
ON t1.id = t2.max_id
WHERE t1.success = 1
// Select Max ID group by person, join with original table, then filter by success
And I'm wondering if there are better approach or neater SQL lines for this?
Thank you so much!