I am struggling with this SQL question for several days. I am quite new to 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:
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. 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. Also, I don't think and w.dayofweek <= 7
is needed.
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
.
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.