4

我花了很多时间来构建这个选择,但我无法解决它。我有 2 张桌子。第一个表称为 car 并具有 PK(主键)id_car 和另一个列名称等。第二个表称为 rating 并具有列 id_rating (PK)、id_car (FK) 和 rating_value (integer)。正如您所怀疑的那样,一辆车可以有不止一个咆哮。我想选择所有汽车,我想知道每辆车的平均评分。最后,我想按这个平均降序对结果进行排序。我正在尝试这样的事情:

    SELECT id_car, name, average
    FROM car C, rating R 
    WHERE C.id_car = R.id_car 
    ORDER BY (average) (
        SELECT AVG(rating_value) AS average 
        FROM rating R
        WHERE C.id_car = R.id_car)

但它不起作用。

4

4 回答 4

5

对于SQL Server; 我也建议你使用JOIN而不是WHERE table1, table2..

SELECT C.id_car, name, AVG(rating_value) AS average
FROM car C JOIN rating R 
      ON C.id_car = R.id_car
GROUP By C.id_car, name
ORDER BY average DESC
于 2012-11-28T11:48:13.997 回答
2

这实现了聚合函数AVG(),然后是GROUP BY汽车 ID 和名称:

select c.id_car, c.name, avg(r.rating_value) aver
from car c
left join rating r
  on c.id_car = r.id_car
group by c.id_car, c.name
order by aver desc

使用 aLEFT JOIN将包括结果中的所有汽车,即使是尚未评级的汽车。

于 2012-11-28T11:49:07.807 回答
0
SELECT C.name, AVG(R.rating_value)
FROM car C, rating R 
WHERE C.id_car = R.id_car
GROUP BY C.name
ORDER BY AVG(R.rating_value) DESC
于 2012-11-28T11:48:31.460 回答
0
 SELECT c.id_car, c.name,avg(r.rating_value) as rating   
FROM car c
 join  rating r 
 on c.id_car = r.id_car   
group by r.id_car 
order by rating
于 2012-11-28T11:49:58.103 回答