简体   繁体   English

如何在SQL中返回每个条件的平均值

[英]How to return average of each condition in SQL

I am struggling with this SQL question for several days. 我为这个SQL问题苦苦挣扎了好几天。 I am quite new to SQL. 我对SQL很陌生。 Really appreciate your time and effort. 非常感谢您的时间和精力。

Q: returns the average arrival delay time for each day of the week. 问:返回一周中每一天的平均到达延迟时间。

Expect results : 预期结果

+--------------+---------------+
| weekday_name |   avg_delay   |
+--------------+---------------+
|    Friday    | 14.4520127056 |
|    Monday    | 10.5375015249 |
|   Thursday   | 8.47985564693 |
|  Wednesday   |  8.4561902339 |
|   Saturday   | 7.54455459234 |
|   Tuesday    | 4.63152453983 |
|    Sunday    | 4.21165978081 |
+--------------+---------------+

I already have two table ready: flight_delays and weekdayName My sql code in ipython book: 我已经准备好两个表:flight_delays和weekdayName我在ipython书中的sql代码:

SELECT distinct w.weekday_name, AVG(f.arr_delay) as average_delay
FROM flight_delays as f, weekdayName as w
WHERE f.day_of_week = w.dayofweek and w.dayofweek <= 7
ORDER BY AVG(arr_delay)

it only returns: 它只会返回:

weekday_name    average_delay
Sunday          8.295147670495197

So it actually average all seven days' results. 因此,它实际上平均了所有7天的结果。 But I want to average results of each day. 但是我想平均每天的结果。 Could you please explain where is my mistake. 你能解释我的错误在哪里。 Thanks a lot. 非常感谢。

First, learn to use proper join and group by syntax. 首先,学习使用正确的joingroup by语法。 Also, I don't think and w.dayofweek <= 7 is needed. 另外,我不认为and w.dayofweek <= 7是必需的。

Does this do what you want? 这是您想要的吗?

SELECT w.weekday_name, AVG(f.arr_delay) as average_delay
FROM flight_delays f join
     weekdayName w
     on f.day_of_week = w.dayofweek 
GROUP BY w.weekday_name
ORDER BY AVG(arr_delay)

Made some adjustments: 进行了一些调整:

SELECT w.weekday_name, AVG(f.arr_delay) as average_delay
FROM flight_delays f INNER JOIN weekdayName w
ON f.day_of_week = w.dayofweek
GROUP BY w.weekday_name
ORDER BY AVG(arr_delay);

If you are doing aggregation(here AVG ) in your SELECT , you need to provide non-aggregation fields in the GROUP BY . 如果要在SELECT中进行聚合(此处为AVG ),则需要在GROUP BY提供非聚合字段。

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

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