从GROUP中选择数据和最新库存

时间:2017-12-14 14:56:31

标签: mysql select join group-by subquery

我必须根据以下示例提出我的问题。

mysql表

enter image description here

第1步:每天获得销售

SELECT SUM(amount) as sold, productnumber, DATE(date) AS date
FROM foo
GROUP BY productnumber, DATE(date)
ORDER BY date;

返回:

enter image description here

第2步/想要:每天获得销售和最新库存

最新股票=每日最后一次股票更新,例如对于产品编号123它在2017-12-06的第7页:

enter image description here

那么如何选择呢?

显然,只需在SELECT中添加库存就不会起作用:

SELECT stock, SUM(amount) as sold, productnumber, DATE(date) AS date
FROM foo
GROUP BY productnumber, DATE(date)
ORDER BY date;

此产品和当天将返回0而不是7:

enter image description here

LEFT JOIN?子查询?

如何正确编写此SQL?

提前致谢!

1 个答案:

答案 0 :(得分:1)

规范方式是join

SELECT f.*, f2.stock
FROM foo f JOIN
     (SELECT f.productnumber, SUM(f.amount) as sold, DATE(f.date) as date,
             MAX(f.date) as maxdate
      FROM foo f
      GROUP BY f.productnumber, DATE(f.date)
     ) f join
     foo f2
     ON f2.productnumber = f.productnumber AND f2.date = f.maxdate
ORDER BY date;