MySQL按日期获取最新数据

时间:2018-11-25 09:15:09

标签: mysql

表库存

stock id cost       date   id   Type
ABC     1000.00 2018-01-01  1   BEGINING_QTY
ABC     2000.00 2018-02-01  2   PURCHASE
ABC     3000.00 2018-02-03  3   PURCHASE
BBB     1000.00 2018-01-01  4   BEGINING_QTY
BBB    20000.00 2018-10-01  5   PURCHASE
BBB    3000.00  2018-10-05  6   PURCHASE

我会得到这样的数据

stock_id   cost     date
ABC        3000      2018-02-03
BBB        3000      2018-10-05

1 个答案:

答案 0 :(得分:0)

这可能会有所帮助。

SELECT inventorys.stock_id,inventorys.date,inventorys.cost
FROM inventorys inventorys
INNER JOIN ( SELECT stock_id, MAX(date) FROM inventorys GROUP BY stock_id ) inv_temp ON inv_temp.date=inventorys.date AND inv_temp.stock_id=inventorys.stock_id