如何在同一结果中选择 Sum 列的平均值

问题描述 投票:0回答:1

我有一张包含日期和数量的操作表。

日期时间 数量
2024-01-01 1
2024-02-5 2

我想对每个月的数量进行求和,然后按每个月进行分组,这样效果很好。

然后我还想对上面的总和进行平均(当年所有数量的平均值)并将最终结果显示在一张表格中。

SUM(数量) 平均(XXX)
01 1860 1648
02 1899 1648
03 1677 1648
04 2166 1648
05 1576 1648
06 1718 1648
07 2144 1648
08 872 1648
09 924 1648
SELECT MONTH(o1.dateTime), SUM(o1.quantity)
FROM operation o1
WHERE o1.dateTime between '2024-01-01' and '2024-12-31'
GROUP BY MONTH(o1.dateTime)
mysql group-by sum aggregate-functions average
1个回答
0
投票

使用任一查询:

SELECT 
    MONTH(o1.dateTime) AS MONTH, 
    SUM(o1.quantity) AS SUM,
    ROUND(SUM(o1.quantity)/COUNT(MONTH(o1.dateTime)), 2) AS AVG
FROM operation o1
WHERE o1.dateTime between '2024-01-01' and '2024-12-31'
GROUP BY MONTH(o1.dateTime)

SELECT 
    MONTH(o1.dateTime) AS MONTH, 
    SUM(o1.quantity) AS SUM,
    ROUND(AVG(o1.quantity), 2) AS AVG
FROM operation o1
WHERE o1.dateTime between '2024-01-01' and '2024-12-31'
GROUP BY MONTH(o1.dateTime)
© www.soinside.com 2019 - 2024. All rights reserved.