SQL过滤两个条件不同的聚合函数
SQL Filter two aggregate functions with different conditions
我想得到
之间的区别
AVG(arr_delay_new)
WHERE fl_date BETWEEN '2017/07/24' AND '2017/07/31'
和
AVG(arr_delay)_new
WHERE fl_date BETWEEN '2017/07/01' AND '2017/07/23'
这个当然 returns 0 并且没有日期条件。
SELECT
airline_name,
AVG(arr_delay_new) - AVG(arr_delay_new)
FROM
Flight_delays F
JOIN
Airlines A ON A.airline_id = F.airline_id
GROUP BY
airline_name
您可以使用条件聚合:
SELECT airline_name,
(AVG(CASE WHEN fl_date BETWEEN '2017-07-24' and '2017-07-31' THEN arr_delay_new END) -
AVG(CASE WHEN fl_date BETWEEN '2017-07-01' and '2017-07-23' THEN arr_delay_new END)
) as AVG_DIFF
FROM Flight_delays F JOIN
Airlines A
ON A.airline_id = F.airline_id
GROUP BY airline_name;
这假定 arr_delay_new
具有可以平均的类型。一些数据库不愿意直接对 date/times 进行平均。
我想得到
之间的区别AVG(arr_delay_new)
WHERE fl_date BETWEEN '2017/07/24' AND '2017/07/31'
和
AVG(arr_delay)_new
WHERE fl_date BETWEEN '2017/07/01' AND '2017/07/23'
这个当然 returns 0 并且没有日期条件。
SELECT
airline_name,
AVG(arr_delay_new) - AVG(arr_delay_new)
FROM
Flight_delays F
JOIN
Airlines A ON A.airline_id = F.airline_id
GROUP BY
airline_name
您可以使用条件聚合:
SELECT airline_name,
(AVG(CASE WHEN fl_date BETWEEN '2017-07-24' and '2017-07-31' THEN arr_delay_new END) -
AVG(CASE WHEN fl_date BETWEEN '2017-07-01' and '2017-07-23' THEN arr_delay_new END)
) as AVG_DIFF
FROM Flight_delays F JOIN
Airlines A
ON A.airline_id = F.airline_id
GROUP BY airline_name;
这假定 arr_delay_new
具有可以平均的类型。一些数据库不愿意直接对 date/times 进行平均。