假设您有以下表格:
TABLE Car
car_id
num
TABLE Car_description
dsc_id
car_id
model
TABLE Result
res_id
car_id
race_num
result
任务是为我们拥有超过 2 辆汽车和 Car.num、Car_description.model 的比赛选择最高、平均分数以获得最佳汽车。解决它的一种方法是编写以下查询。
select r.race_num,
MAX(score) as MaxScore,
AVG(score) as AvgScore,
MAX(case when seqnum = 1 then c.carnum end) as TopCarNum,
MAX(case when seqnum = 1 then cd.model end) as TopCarModel
from (select r.*,
ROW_NUMBER() over (partition by race_num order by score desc) as seqnum
from Result r
) r left outer join
Car c
on c.car_id = r.car_id left outer join
Car_Description cd
on c.car_id = d.car_id
group by r.race_num
having COUNT(*) > 2
但是这里我们在内部查询中对结果表进行排序,而不是选择最大元素,我认为这会很耗时。是这样吗?我们该如何优化呢?谢谢。