简体   繁体   中英

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

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   

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