I've tried various queries and read different answers to this and nothing seems to give EXACTLY what I'm looking for. Advice is appreciated.
I have a table with items, dates and quantities. For each item, I need the latest date and associated quantity. The table looks like this:
item date qty
1234 2014-12-22 300
1234 2015-02-13 500
After running this query:
SELECT item, MAX(date), qty
FROM table
GROUP BY item
I get this:
item date qty
1234 2015-02-13 300
Instead of a qty
of 500
. I've tried a couple of different solutions including this and this. The first one gave all the records with NULL
in date
. The second one seems to work, until I try to do SUM(qty)
(there can be multiple qty
for an item
on any given date
). Since this solution sorts by date
descending, and does not actually cut out any data, it doesn't help in this scenario.
Why does my original query not work? Any other ideas?
Thanks!