![](/img/trans.png)
[英]MySQL average of 2 columns using WHERE and GROUP BY year(), month()
[英]Mysql get average and sum of columns and group by year & month
我有一个查询,其中我需要返回价格的平均值和数量的总和,并将结果按年和月分组。 这是我查询的开始,只是不知道如何获得所需的结果。
SELECT asin,
price,
qtyTotal,
qtyReserved,
qtyWarehouse,
qtyFulfillable,
qtyUnsellable,
perUnitVolume,
YEAR(reportDate),
MONTH(reportDate),
DAY(reportDate)
FROM Table
WHERE name = 'XXXXXXX'
ORDER BY reportDate ASC
id | name | price | qty | unitVol | year | month | day | reportDate
---|-----------------------------------------------------------------------------
1 | XXXXXXX | 20.18 | 3 | 0.17 | 2014 | 8 | 23 | 2014-8-23
2 | XXXXXXX | 20.19 | 3 | 0.18 | 2015 | 11 | 10 | 2014-8-23
3 | XXXXXXX | 20.21 | 3 | 0.19 | 2015 | 11 | 11 | 2014-8-23
4 | XXXXXXX | 20.22 | 3 | 0.20 | 2015 | 11 | 12 | 2014-8-23
5 | XXXXXXX | 20.43 | 3 | 0.11 | 2015 | 12 | 1 | 2014-8-23
6 | XXXXXXX | 23.34 | 3 | 0.13 | 2015 | 12 | 2 | 2014-8-23
7 | XXXXXXX | 25.54 | 3 | 0.19 | 2015 | 12 | 3 | 2014-8-23
这是我需要结束的结果:
id | name | price | qty | unitVol | year | month
---|------------------------------------------------------------------
1 | XXXXXXX | 20.18 | 3 | 0.17 | 2014 | 8
2 | XXXXXXX | 20.21 | 9 | 0.19 | 2015 | 11
3 | XXXXXXX | 23.10 | 9 | 0.14 | 2015 | 12
价格是具有相同年份和月份的每个记录的平均价格,例如记录ID#2为:(20.19 + 20.21 + 20.22)/ 3 = 20.21
数量是年和月记录的总和,例如记录ID#2为:3 + 3 + 3 = 9
谢谢你的帮助。
SELECT id, name, AVG(price), SUM(qty), AVG(unitVol), year, month
FROM Table
WHERE name = 'XXXXXXX'
GROUP BY year, month
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.