Arun
Arun

Reputation: 146

Get last record in every month - mysql

In my db i have stored price of products for everyday.

I need records based on last record of every month.

when i apply group by month, it is giving the first record of the month.

Query i have tried was,

select * from product where product_id = 52   
AND YEAR(date_modified) = YEAR(NOW()) GROUP BY MONTH(date_modified)

Any ideas are welcome

Upvotes: 0

Views: 1095

Answers (1)

jarlh
jarlh

Reputation: 44766

Have a derived table where you using GROUP BY find each product's latest date per month. Join with that derived table:

select * from
product t1
join (select product_id, max(date_modified) max_date_modified from product
      group by product_id, YEAR(date_modified), MONTH(date_modified)) t2
  on t1.product_id = t2.product_id and t1.date_modified = t2.max_date_modified
where product_id = 52   

Upvotes: 2

Related Questions