How can I get the latest product title when I'm doing a group by category?
For example, assume this is my table of products:
id | title | catID | timestamp
1 | apple | 1 | 2020-07-13 08:21:47
2 | pear | 1 | 2020-07-14 08:21:47
3 | kiwi | 1 | 2020-07-15 08:21:47
I want a query to give me the total products and the last added. It's a little greedy of a query, and makes it a little more difficult, but I thought I could do this with a group by. If possible, I'd really prefer to keep this all one query. I'm worried I'll need to add a sub query though.
SELECT
p.catID
, COUNT(p.id) as items
, MAX(p.id) as last_added_id
, CASE WHEN p.id = MAX(p.id) THEN p.title
FROM products p
WHERE p.catID = 1
GROUP BY p.catID
The problem is, I'm getting a null for the title.