我有一张桌子,其中包含飞往伦敦的航班。 每个连接都有其特定的ID。每天每个ID可能有多个价格不同的记录。我正在寻找每天最高的连接价格+每天飞往伦敦的任何航班的平均价格。
这是我的查询
SELECT entryDate, MAX(totalPrice) AS totalPrice
FROM flights
WHERE connectionID = 'xyz123'
GROUP BY entryDate
UNION ALL
SELECT entryDate, AVG(totalPrice) AS averagePrice
FROM flights
WHERE destination = 'London'
GROUP BY entryDate
ORDER BY entryDate ASC
LIMIT 90
这是结果:
entryDate totalPrice
2019-05-16 1159.8462
2019-05-16 553.0000
2019-05-17 1164.5736
2019-05-17 553.0000
2019-05-18 1101.8872
2019-05-18 634.0000
2019-05-19 1081.9766
2019-05-19 634.0000
2019-05-20 1119.6250
2019-05-20 634.0000
2019-05-21 1074.5781
2019-05-22 1079.2923
2019-05-23 1060.1641
2019-05-24 1116.1550
请注意,最近4天(21〜24)的MAX(totalPrice)的结果不可用,因为特定的连接'xyz123'不在运行中。
无论如何,我的目的是获得以下结果:
entryDate totalPrice averagePrice
2019-05-16 553.0000 1159.8462
2019-05-17 553.0000 1164.5736
2019-05-18 634.0000 1101.8872
2019-05-19 634.0000 1081.9766
2019-05-20 634.0000 1119.6250
答案 0 :(得分:0)
使用条件聚合:
SELECT entryDate,
MAX(CASE WHEN connectionID = 'xyz123' THEN totalPrice END) AS totalPrice,
AVG(CASE WHEN destination = 'London' THEN totalPrice END) as averagePrice
FROM flights f
GROUP BY entryDate;
如果您只希望同时具有两个 值的天:
SELECT entryDate,
MAX(CASE WHEN connectionID = 'xyz123' THEN totalPrice END) AS totalPrice,
AVG(CASE WHEN destination = 'London' THEN totalPrice END) as averagePrice
FROM flights f
WHERE connectionID = 'xyz123' OR
destination = 'London'
GROUP BY entryDate
HAVING SUM( connectionID = 'xyz123' ) > 0 AND
SUM( destination = 'London' ) > 0;
如果您对日期只满意一个值,请忽略HAVING
子句。