简体   繁体   中英

Select most recent row per item per month

I'm looking to create a summary of inventory items, showing the most recent row for each month.

For example, my table has:

id, date, item, quantity

I'd like to get one row returned per item for each month showing the quantity last reported each month.

Something like:

1, (July datetime), Banana, 5
3, (July datetime), Apple, 2
4, (August datetime), Banana, 6
8, (August datetime), Apple, 8

Thanks for any help!!

What I've tried so far is this:

SELECT t1.*
FROM inventory t1
WHERE t1.date = (SELECT MAX(t2.date)
             FROM inventory t2
             WHERE t2.item = t1.item)

That will, of course, show the most recent row for each item... but not for each month.

MySQL GROUP BY extension allows you to do it in a following way

SELECT id, date, item, quantity
  FROM
(
  SELECT id, date, item, quantity
    FROM inventory
   ORDER BY item, date DESC
) q
 GROUP BY YEAR(date), MONTH(date), item

A more standard way will be to pull MAX date per item per month first and then join back to inventory to grab all other fields

SELECT i.id, i.date, i.item, i.quantity
  FROM
(
  SELECT item, MAX(date) date
    FROM inventory
   GROUP BY item, YEAR(date), MONTH(date) 
) q JOIN inventory i
    ON q.item = i.item
   AND q.date = i.date
 ORDER BY YEAR(i.date), MONTH(i.date), i.item

Here is SQLFiddle demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM