我必须根据以下示例提出我的问题。
SELECT SUM(amount) as sold, productnumber, DATE(date) AS date
FROM foo
GROUP BY productnumber, DATE(date)
ORDER BY date;
返回:
最新股票=每日最后一次股票更新,例如对于产品编号123它在2017-12-06的第7页:
那么如何选择呢?
显然,只需在SELECT中添加库存就不会起作用:
SELECT stock, SUM(amount) as sold, productnumber, DATE(date) AS date
FROM foo
GROUP BY productnumber, DATE(date)
ORDER BY date;
此产品和当天将返回0而不是7:
如何正确编写此SQL?
提前致谢!
答案 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;