简体   繁体   English

Mysql:按月搜索数据只会产生一个结果,而不是全部

[英]Mysql: Searching for data by month only yields one result not all of them

I have an Orders table with the Date_ordered column. 我有一个带有Date_ordered列的Orders表。

I am trying to select the average price of all of the items ordered that were purchased in the month of December. 我正在尝试选择在12月份购买的所有订购商品的平均价格。

I used 我用了

select *, avg(price) from orders where monthname(date_ordered) = "december"

However it is only coming up with one result, when my table has 4 instances of the date being xxxx-12-xx 但是,当我的表中有4个日期为xxxx-12-xx的实例时,只会得出一个结果

Note: There are multiple years included in the data but they are irrelevant to the query I need 注意:数据中包含多年,但与我需要的查询无关

avg() in your query is a group function. 查询中的avg()是一个组函数。 If there is no GROUP BY clause in your query, it causes the group function to be applied on all selected rows. 如果查询中没有GROUP BY子句,则会导致将group函数应用于所有选定的行。 So you are getting average of the four prices in that field. 因此,您将获得该字段中四个价格的平均值。 And the average is only one. 而且平均值只有一个。

When you put avg() into the select , you turn the query into an aggregation query. avg()放入select ,会将查询转换为聚合查询。 Without a group by , SQL always returns on row. 没有group by ,SQL 总是在行上返回。 If you want the average as well as the other data, then use a join or subselect: 如果你想在平均以及其他数据,然后使用一个join或子查询:

select o.*, oo.avgp
from orders o cross join
     (select avg(price) as avgp from orders where month(date_ordered) = 12) oo
where month(o.date_ordered) = 12;

AVG() is an aggregate function. AVG()是一个聚合函数。 It averages every value in the price column and condenses the result into a single row. 它平均价格列中的每个值,并将结果压缩为一行。 You could group your result by another column, or consider if you really want to use avg() 您可以将结果按另一列分组 ,或者考虑是否要使用avg()

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

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