如何在MySQL中按年份统计订单的数量、总金额及关联商品总数量
MySQL按年份统计订单数据方案
现有业务数据表结构
订单表
| 订单ID | 创建日期 | 订单金额 |
|---|---|---|
| 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 |
订单详情表
| 详情ID | 关联订单ID | 商品数量 |
|---|---|---|
| 1 | 1 | 10 |
| 2 | 2 | 20 |
| 3 | 1 | 30 |
| 4 | 3 | 10 |
| 5 | 3 | 20 |
| 6 | 4 | 30 |
| 7 | 5 | 20 |
统计需求
按订单创建日期的年份分组,计算每年的订单总数量、订单总金额、关联商品总数量,期望输出格式如下:
| year(created_date) | orders_count | product_quantity_in_orders | price |
|---|---|---|---|
| 2021 | 2 | 60 | 150 |
| 2020 | 2 | 60 | 200 |
| 2019 | 1 | 20 | 100 |
注:原始给出的期望输出中2020年订单总金额标注为150属于笔误,按表中实际数据计算结果为200
实现查询语句
SELECT YEAR(o.created_date) AS `year(created_date)`, COUNT(DISTINCT o.id) AS orders_count, SUM(od.order_total_qty) AS product_quantity_in_orders, SUM(o.price) AS price FROM `order` o LEFT JOIN ( -- 先统计每个订单对应的商品总数量,避免直接关联导致订单数据重复计数 SELECT order_id, SUM(product_quantity) AS order_total_qty FROM order_details GROUP BY order_id ) od ON o.id = od.order_id GROUP BY YEAR(o.created_date) ORDER BY YEAR(o.created_date) DESC;
内容的提问来源于stack exchange,提问作者java dev
相关产品推荐
相关产品推荐

