我有一张包含日期和数量的操作表。
日期时间 | 数量 |
---|---|
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)
使用任一查询:
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)