【问题标题】:select average quantity sold per month over last 3 month选择过去 3 个月每月的平均销售量
【发布时间】:2017-03-26 12:42:35
【问题描述】:

我有 3 个mysql 表,如下所示:

 - product(product_id, product_name)
 - order(order_id, order_date)
 - order_detail(order_detail_id, product_id, order_id, quantity)

我想获取过去三个月计算的每月销售产品数量的平均值并按产品分组

我想选择所有产品(最近三个月售出或未售出)。

 product_name | avg_quantity_sold_per_month
--------------|-----------------------------
  product_1   | 50
  product_2   | 0
  product_3   | 78

我试过这个查询:

 select 
    p.product_name
  , sum(od.quantity)/3 as avg_quantity_sold_per_month
 from order o
  inner join order_detail od on o.order_id = od.order_id
  inner join product p on od.product_id = p.product_id
 where 
   o.order_date >= now()-interval 3 month 
 group by p.product_id

但它只显示上个月销售的产品,我想选择所有产品。

【问题讨论】:

  • 您的查询中有错字。订单日期来自o 而不是od

标签: mysql sql


【解决方案1】:

使用left join:

select p.product_name,
    sum(od.quantity) / 3 as avg_quantity_sold_per_month
from product p
left join order_detail od on od.product_id = p.product_id
left join orders o on o.order_id = od.order_id
    and o.order_date >= now() - interval 3 month
group by p.product_id

另外,尽量不要使用保留关键字如order 作为标识符。

【讨论】:

  • 我会先从product 表开始加入,从那里开始左加入。
  • 由于 where 子句,你的右连接将被转换为内连接。
  • @GurV order_detail 表中不存在 order_date 字段
  • @dontgav - 我刚刚修改了你给定的查询。总之,更新了。请立即尝试。
【解决方案2】:

如果你想要所有产品,你想要left join

select p.product_name,
       sum(od.quantity) / 3 as avg_quantity_sold_per_month
from product p left join
     order_detail od
     on od.product_id = p.product_id left join
     orders o
     on o.order_id = od.order_id and
        o.order_date >= now() - interval 3 month 
group by p.product_name;

使用left join,您将从要保留的表开始。 (right join 将重要信息留在 last 表中,这很难遵循)。 where 条件需要移动到on 子句,这样不匹配的产品就不会被过滤掉。

请注意,我还更改了 group by 键以匹配所选择的键。这是最佳做法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-03
    • 1970-01-01
    • 1970-01-01
    • 2015-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-18
    相关资源
    最近更新 更多