简体   繁体   中英

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

I have an Orders table with the Date_ordered column.

I am trying to select the average price of all of the items ordered that were purchased in the month of December.

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

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. If there is no GROUP BY clause in your query, it causes the group function to be applied on all selected rows. 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. Without a group by , SQL always returns on row. If you want the average as well as the other data, then use a join or subselect:

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. 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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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