[英]How to select some rows from a table but average values from WHOLE column in T-SQL?
I have a database of airlines delays and I need to average the delays of their ALL flights by air line but then display only the air lines that fly from city X.我有一个航空公司延误的数据库,我需要按航空公司平均他们所有航班的延误,然后只显示从 X 市起飞的航空公司。
I tried this code:我试过这段代码:
SELECT
B.airline_name,
AVG(A.arrival_delay) avg_delay
FROM
TableDelays A
JOIN
TableAirlines B ON A.airline_id = B.airline_id
WHERE
A.city = 'X'
GROUP BY
B.airline_name
But when I use WHERE Origin = 'X'
line, I get incorrect average delay of only the flights that departure from city X. Whereas, when I don't use the WHERE line, I have all air lines with correct averages displayed (from all their flights), but I only need to display the ones from city X.但是,当我使用WHERE Origin = 'X'
线时,我得到的只有从 X 市出发的航班的平均延误不正确。而当我不使用 WHERE 线时,我会显示所有具有正确平均值的航空公司(从他们所有的航班),但我只需要显示来自 X 市的航班。
Does anyone know how to "extract" only the air lines departing from city X so that I don't take it into consideration while averaging the values?有谁知道如何仅“提取”从 X 市出发的航空公司,这样我在计算平均值时就不会考虑它?
Use a HAVING
clause:使用HAVING
子句:
SELECT ta.airline_name,
AVG(td.arrival_delay) as avg_delay
FROM TableDelays td JOIN
TableAirlines ta
ON td.airline_id = ta.airline_id
GROUP BY ta.airline_name
HAVING SUM(CASE WHEN td.city = 'X' THEN 1 ELSE 0 END) > 0
Perhaps a CTE would help achieve this?也许 CTE 将有助于实现这一目标?
WITH CTE AS(
SELECT TA.airline_name,
AVG(TD.arrival_delay) AS avg_delay,
MAX(CASE WHEN TD.City = 'X' THEN 1 END) AS XCity
FROM dbo.TableDelays TD --"A" is a poor choice for an alias here
JOIN dbo.TableAirlines TA ON TD.airline_id = TA.airline_id --"B" doesn't even appear in "Airlines", why use it?
GROUP BY TA.airline_name)
SELECT airline_name,
avg_delay
FROM CTE
WHERE XCity = 1;
As I note in my comments A
, and B
are poor choices for your table alias.正如我在评论中指出的那样, A
和B
是您的表别名的糟糕选择。 Use suitable ones when giving your tables aliases.给表别名时使用合适的别名。 Bad habits to kick: using table aliases like (a, b, c) or (t1, t2, t3) 要改掉的坏习惯:使用表别名,如 (a, b, c) 或 (t1, t2, t3)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.