每个月的平均订单价值是多少?

问题描述 投票:0回答:0

所以我在 MySQL 中有两个表:“orders”和“order_items”。

插入订单(客户 ID、订单日期、状态)值
(1, '2022-01-01 10:00:00', '待定'),
(2, '2022-01-02 11:00:00', '已发货'),
(3, '2022-01-03 12:00:00', '已送达'),
(2, '2022-01-04 09:00:00', '已发货'),
(1, '2022-02-01 10:00:00', '待定'),
(2, '2022-03-01 11:00:00', '已发货'),
(3, '2022-04-01 12:00:00', '已送达');

插入 order_items(order_id、product_id、数量、价格)
值(1、1、2、19.99),
(1, 3, 1, 59.99),
(2, 2, 1, 39.99),
(2, 4, 1, 99.99),
(2, 5, 1, 49.99),
(3, 1, 3, 19.99),
(3, 3, 2, 59.99),
(3, 5, 2, 49.99),
(4, 3, 5, 59.99),
(5, 1, 2, 19.99),
(5, 2, 1, 39.99),
(6,3, 1 , 59.99),
(6, 3, 2, 59.99),
(6, 4, 1, 99.99),
(7, 5, 2, 49.99);

我正在尝试解决:每个月的平均订单价值是多少?

select month(order_date) as month, avg(quantity * price)
from order_items oi join orders o on oi.order_id = o.order_id 
group by month; 

这就是我所做的

with cte as 
(select order_id, sum(quantity * price) as total
from order_items 
group by order_id)

select month(order_date) as month, avg(total) from orders oi 
    join cte 
      on oi.order_id = cte.order_id 
group by month;

这似乎是正确的答案。为什么这会改变平均值。

我需要知道为什么这两行代码会产生不同的结果,而不是为两种方法找到相同的平均值。

mysql group-by average
© www.soinside.com 2019 - 2024. All rights reserved.