如何 return SQL 中每个条件的平均值
How to return average of each condition in SQL
我为这个 SQL 问题苦苦挣扎了好几天。我对 SQL 很陌生。非常感谢您的时间和精力。
问:returns一周中每一天的平均到达延迟时间。
期待结果:
+--------------+---------------+
| 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 |
+--------------+---------------+
我已经准备好了两个 table:flight_delays 和 weekdayName
我的 sql 代码在 ipython 书中:
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)
只有 returns:
weekday_name average_delay
Sunday 8.295147670495197
所以它实际上是对所有 7 天的结果进行平均。但我想平均每天的结果。你能解释一下我的错误在哪里吗?非常感谢。
首先,学习使用正确的 join
和 group by
语法。另外,我认为不需要and w.dayofweek <= 7
。
这是你想要的吗?
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)
做了一些调整:
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);
如果您在 SELECT
中进行聚合(此处 AVG
),则需要在 GROUP BY
.
中提供非聚合字段
我为这个 SQL 问题苦苦挣扎了好几天。我对 SQL 很陌生。非常感谢您的时间和精力。
问:returns一周中每一天的平均到达延迟时间。
期待结果:
+--------------+---------------+
| 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 |
+--------------+---------------+
我已经准备好了两个 table:flight_delays 和 weekdayName 我的 sql 代码在 ipython 书中:
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)
只有 returns:
weekday_name average_delay
Sunday 8.295147670495197
所以它实际上是对所有 7 天的结果进行平均。但我想平均每天的结果。你能解释一下我的错误在哪里吗?非常感谢。
首先,学习使用正确的 join
和 group by
语法。另外,我认为不需要and w.dayofweek <= 7
。
这是你想要的吗?
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)
做了一些调整:
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);
如果您在 SELECT
中进行聚合(此处 AVG
),则需要在 GROUP BY
.