如何计算 MYSQL 中按年分组的订单统计?
How to calculate Statistics for orders group by year in MYSQL?
订单table.
id
created_date
price
1
2021-09-01
100
2
2021-09-01
50
3
2020-09-01
50
4
2020-09-01
150
5
2019-09-01
100
订单详情table:-
id
order_id
product_quantity
1
1
10
2
2
20
3
1
30
4
3
10
5
3
20
6
4
30
7
5
20
所以我需要一个 MySQL 查询来获取有关每年的订单数量、价格和产品数量的统计信息。
预期的 table
year(created_date)
orders_count
product_quantity_in_orders
price
2021
2
60
150
2020
2
60
150
2019
1
20
100
请试试这个。
SELECT YEAR(o.created_date) year_created
, COUNT(o.id) orders_count
, SUM(t.product_quantity) product_quantity_in_orders
, SUM(o.price) price
FROM orders o
INNER JOIN (SELECT order_id
, SUM(product_quantity) product_quantity
FROM order_details
GROUP BY order_id) t
ON o.id = t.order_id
GROUP BY YEAR(o.created_date)
订单table.
id | created_date | price |
---|---|---|
1 | 2021-09-01 | 100 |
2 | 2021-09-01 | 50 |
3 | 2020-09-01 | 50 |
4 | 2020-09-01 | 150 |
5 | 2019-09-01 | 100 |
订单详情table:-
id | order_id | product_quantity |
---|---|---|
1 | 1 | 10 |
2 | 2 | 20 |
3 | 1 | 30 |
4 | 3 | 10 |
5 | 3 | 20 |
6 | 4 | 30 |
7 | 5 | 20 |
所以我需要一个 MySQL 查询来获取有关每年的订单数量、价格和产品数量的统计信息。
预期的 table
year(created_date) | orders_count | product_quantity_in_orders | price |
---|---|---|---|
2021 | 2 | 60 | 150 |
2020 | 2 | 60 | 150 |
2019 | 1 | 20 | 100 |
请试试这个。
SELECT YEAR(o.created_date) year_created
, COUNT(o.id) orders_count
, SUM(t.product_quantity) product_quantity_in_orders
, SUM(o.price) price
FROM orders o
INNER JOIN (SELECT order_id
, SUM(product_quantity) product_quantity
FROM order_details
GROUP BY order_id) t
ON o.id = t.order_id
GROUP BY YEAR(o.created_date)