2

假设您有以下表格:

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 
race_num,
MAX(result),
AVG(result),
STDDEV(result)
FROM Result r, Car c, Car_description d
WHERE c.car_id = r.car_id AND d.car_id = c.car_id
HAVING COUNT(result) > 2
GROUP BY r.race_num

但我不明白 - 如何为每场比赛选择最好的车号和型号?谢谢。

4

1 回答 1

1

我假设 car_id 是从 car 到 car_description 的 1-1 映射。

下面的查询使用 row_number() 根据分数获取排名靠前的汽车。此信息可能已经存在于“结果”中。

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

关键是分组,有条件地选择有关顶级汽车的信息。

于 2012-09-05T14:44:49.723 回答