我有3个mysql表,如下所示:
我希望获得过去3个月内销售的产品数量总和,并将产品分类为:
product_id | quantity_sold_last_3_mouth
1 | 50
2 | 156
3 | 78
问题是如何仅连接创建最后三个月的表order_detail的行,因为日期仅按表顺序设置
非常感谢任何想法或帮助
答案 0 :(得分:0)
取决于您定义“过去3个月”的方式:
select
od.product_id
, sum(od.quantity) as quantity_sold_last_3_month
from order o
inner join order_detail od
on o.order_id = od.order_id
where
o.order_date >= last_day(now()) + interval 1 day - interval 3 month #first of month, e.g. Jan 1 from today March 25
#od.order_date >= now()-interval 3 month #exactly 3 months back, e.g. Dec 25 from today
group by od.product_id