mysql之无法同时获得月总和和每个月每天的平均总和
lidabo
阅读:80
2024-12-31 21:38:35
评论:0
我有一个表 orders
,我需要获取每个月的 order_sum
总和。这很容易使用组。但是我还需要获得每个月每天的平均金额。我正在使用联接,以便稍后对结果进行排序。 (我使用的是 MySQL 5.6 版)
我收到一个错误:
Unknown column 'orders.month' in 'on clause'
这是我的订单
表:
+----+-----------+---------------------+
| id | order_sum | created_at |
+----+-----------+---------------------+
| 1 | 25.13 | 2020-01-05 08:02:17 |
| 2 | 1.01 | 2020-01-25 20:13:20 |
| 3 | 5.04 | 2020-01-29 16:11:56 |
| 4 | 39.57 | 2020-02-17 15:14:09 |
| 5 | 63.01 | 2020-02-28 17:13:55 |
| 6 | 7 | 2020-03-02 07:10:02 |
+----+-----------+---------------------+
这是我的查询:
select
MONTH(created_at) as month,
sum(order_sum) as order_sum,
second_table.avg_order_sum as average_per_day
from
orders
inner join (
select
month(created_at) as month,
avg(order_sum) as avg_order_sum
from
orders
) as second_table on orders.month = second_table.month
group by
month;
这是我想要得到的结果
+-------+-----------+-----------------+
| month | order_sum | average_per_day |
+-------+-----------+-----------------+
| 1 | 31.18 | 10.39 |
| 2 | 102.58 | 51.29 |
| 3 | 7 | 7 |
+-------+-----------+-----------------+
我知道我可以使用这个简单的查询轻松获得每天的平均值,但我无法使用内部联接将其合并到一个查询中...
select month(created_at) as month, avg(order_sum) as average_per_day from orders group by month
这是模式
CREATE TABLE orders(
id INTEGER NOT NULL PRIMARY KEY,
order_sum NUMERIC(11,2) NOT NULL,
created_at VARCHAR(21) NOT NULL
);
INSERT INTO orders(id, order_sum, created_at) VALUES
(1, 25.13, '2020-01-05 08:02:17'),
(2, 1.01, '2020-01-25 20:13:20'),
(3, 5.04, '2020-01-29 16:11:56'),
(4, 39.57, '2020-02-17 15:14:09'),
(5, 63.01, '2020-02-28 17:13:55'),
(6, 7.00, '2020-03-02 07:10:02');
这是一个带有模式的 fiddle : http://sqlfiddle.com/#!9/b6b15/10
请您参考如下方法:
你可以简单地尝试:
SELECT month(created_at) AS month
,sum(order_sum) AS Order_Sum
,avg(order_sum) AS average_per_day
FROM orders
GROUP BY month
声明
1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。