我有一个表orders
,我需要每个月获取order_sum
的总和。使用组很容易。但是,然后我还需要获取每个月每天的平均金额。我正在使用联接,以便以后可以对结果进行排序。 (我正在使用MySQL版本5.6)
我遇到错误:
[on子句中的未知列'orders.month']
这是我的orders
表:
+----+-----------+---------------------+
| 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');
[这里是有关架构的小提琴:http://sqlfiddle.com/#!9/b6b15/10
您需要在MONTH(created_at)
和GROUP BY
中引用JOIN ON
(不是别名),并且还要对second_table
进行分组。这对我有用:
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
group by month(created_at)
) as second_table on MONTH(created_at) = second_table.month
group by
MONTH(created_at);
您可以简单地尝试:
SELECT month(created_at) AS month
,sum(order_sum) AS Order_Sum
,avg(order_sum) AS average_per_day
FROM orders
GROUP BY month