所以我有一个包含一组订单项目的表,订单项目表跟踪特定订单中包含多少特定项目。下面是此示例中使用的表格的简化版本。
订单项表
order_item_id : int
order_item_item_id : int
order_item_quantity : int
order_item_order_id : int
订单表
order_id : int
order_date : date
我正在尝试执行一个查询,该查询将平均每周、每月和所有时间的特定 order_item_item_id 的销售额。
目前我的查询如下
SELECT totalAvg.item
ROUND(AVG(totalAvg.total)+0.4999999, 0) AS totalAverage,
ROUND(AVG(monthAvg.total)+0.4999999, 0) AS monthAverage,
ROUND(AVG(weekAvg.total)+0.4999999, 0) AS weekAverage from
(SELECT orderitem.order_item_item_id AS item, SUM(orderitem.order_item_quantity) AS total,
DATE(`order`.order_date) AS date FROM orderitem, `order` WHERE orderitem.order_item_order_id =
`order`.order_id GROUP BY DATE(`order`.order_date), order_item_item_id) AS totalAvg,
(SELECT orderitem.order_item_item_id AS item, SUM(orderitem.order_item_quantity) AS total,
DATE(`order`.order_date) AS date FROM orderitem, `order` WHERE orderitem.order_item_order_id =
`order`.order_id AND `order`.order_date > date_sub(now(), interval 1 week) GROUP BY
DATE(`order`.order_date), order_item_item_id) AS weekAvg,
(SELECT orderitem.order_item_item_id AS item, SUM(orderitem.order_item_quantity) AS total,
DATE(`order`.order_date) AS date FROM orderitem, `order` WHERE orderitem.order_item_order_id =
`order`.order_id AND `order`.order_date > date_sub(now(), interval 1 month) GROUP BY
DATE(`order`.order_date), order_item_item_id) AS monthAvg,
WHERE totalAvg.item = monthAvg.item AND
monthAvg.item = weekAvg.item
GROUP BY item
这样做的问题是,如果 weekAvg 表中不存在项目,则不会为 totalAvg 或 monthAvg 打印任何结果。我怎样才能在单个语句中执行此操作?
样本数据
{order_id : 5, order_date : 02/02/2013}
{order_id : 6, order_date : 13/03/2013}
{order_item_id : 1, order_item_order_id : 5, order_item_item_id : 1, order_item_quantity : 3}
{order_item_id : 2, order_item_order_id : 6, order_item_item_id : 1, order_item_quantity : 4}
当前输出不会返回任何内容,因为每周报告没有 id 为 1 的订单项的条目。我试图解决这个问题,以便它输出以下内容
totalAverage = 3.5
monthAverage = 4
weekAverage = 0
这些值的计算如下:
总平均数 = 售出的特定商品的总数除以该商品的售出天数。
月和周值与之前的计算相同,但有时间限制,因此订单必须在上周/月内下达。