You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在MySQL中按年份统计订单的数量、总金额及关联商品总数量

MySQL按年份统计订单数据方案

现有业务数据表结构

订单表

订单ID创建日期订单金额
12021-09-01100
22021-09-0150
32020-09-0150
42020-09-01150
52019-09-01100

订单详情表

详情ID关联订单ID商品数量
1110
2220
3130
4310
5320
6430
7520

统计需求

按订单创建日期的年份分组,计算每年的订单总数量、订单总金额、关联商品总数量,期望输出格式如下:

year(created_date)orders_countproduct_quantity_in_ordersprice
2021260150
2020260200
2019120100

注:原始给出的期望输出中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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 01:48:05