My database table name is ledgers and fields are id, item_id, date, …other fields
I Want the last record from (groupBy item_id order by date ASC). from each group. I tried below query
select `id`, `item_id`, `date`, `opening_quantity`, `closing_quantity`, `item_rate`, `item_value`, `previous_rate` from `ledgers` where date(`date`) >= ? and date(`date`) <= ? group by `item_id` order by `date` desc
Can you guys please help.
Advertisement
Answer
You can filter with a correlated subquery:
select t.* from `ledgers` t where date(t.`date`) >= ? and date(t.`date`) <= ? and t.`date` = ( select max(t1.`date`) from `ledgers` t1 where t1.`item_id` = t.`item_id` )
For performance, consider an index on (item_id, date)
.
Another option is to use rank()
(available in MySQ 8.0 only):
select * from ( select t.*, rank() over(partition by `item_id` order by `date` desc) rn from `ledgers` t where date(t.`date`) >= ? and date(t.`date`) <= ? ) t where rn = 1