简体   繁体   English

MySQL-选择中每个月的平均值

[英]MySQL - Getting average for each month in select

I have a demo table with a list of dates, the type of toy, age group of toy, and sales figure. 我有一个演示表,其中列出了日期,玩具类型,玩具年龄组以及销售量。 I want to grab a list of sales ordered by month, but the average for each month: 我想获取按月订购的销售清单,但每个月的平均值:

Table
Date | Type | Age | Sales
2014-01-04 | Blocks | 3+ | 1000
2014-01-12 | Blocks | 3+ | 2000
2014-01-23 | Blocks | 3+ | 1500
2014-02-04 | Blocks | 3+ | 1000
2014-02-12 | Blocks | 3+ | 3500
2014-02-23 | Blocks | 3+ | 700
2014-03-04 | Blocks | 3+ | 1100
2014-04-12 | Blocks | 3+ | 2100
2014-04-23 | Blocks | 3+ | 1200

Thinking larger scale ie thousands of records, does the below query look right or is there a better way of doing it? 考虑更大的规模,即成千上万的记录,下面的查询看起来正确还是有更好的方法呢?

SELECT YEAR(Date) AS MyYear,MONTH(Date) AS MyMonth,AVG(Sales) AS MyValue
FROM SalesTable
WHERE Type LIKE 'Blocks%' AND Age='3+'
GROUP BY MyYear, MyMonth;

Avoid using LIKE unnecessarily. 避免不必要地使用LIKE。 In you sample there is no need for LIKE. 在您的样本中,不需要LIKE。 This can impact your performance when data grows. 当数据增长时,这可能会影响您的性能。

Type LIKE 'Blocks%' 

Also you may want to consider indexing Type and Age column. 另外,您可能需要考虑为“类型”和“年龄”列编制索引。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM