Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't get both the sum of month and also the average sum per day of each month

Tags:

sql

mysql

I have a table orders and I need to get the sum of order_sum for each month. That is easy using group. But then I also need to get the average sum per day for each month. I am using joins so I can sort the results later. (I'm using MySQL version 5.6)

I am getting an error:

Unknown column 'orders.month' in 'on clause'

Here is my orders table:

+----+-----------+---------------------+
| 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 |
+----+-----------+---------------------+

Here is my query:

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;

This is the result that I am trying to get

+-------+-----------+-----------------+
| month | order_sum | average_per_day |
+-------+-----------+-----------------+
| 1     | 31.18     | 10.39           |
| 2     | 102.58    | 51.29           |
| 3     | 7         | 7               |
+-------+-----------+-----------------+

I know that I can easily get the average per day using this simple query but I'm unable to merge this into one query using inner join...

select month(created_at) as month, avg(order_sum) as average_per_day from orders group by month

And here is the schema

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');

Here is a fiddle with schema: http://sqlfiddle.com/#!9/b6b15/10

like image 775
Liga Avatar asked Dec 15 '25 16:12

Liga


1 Answers

You can simply try like:

SELECT month(created_at) AS month
    ,sum(order_sum) AS Order_Sum
    ,avg(order_sum) AS average_per_day
FROM orders
GROUP BY month
like image 151
apomene Avatar answered Dec 17 '25 14:12

apomene



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!