2

我的桌子是:

CREATE TABLE Rating
(
    rid INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
    mid INTEGER FOREIGN KEY REFERENCES Movie(movieId) ON DELETE CASCADE, 
    uid INTEGER FOREIGN KEY REFERENCES User(id) ON DELETE CASCADE,
    rating INTEGER NOT NULL, 
);

我想选择平均评分最高的中档:

select avg(r.rating) from rating r

女巫返回平均值。我想返回平均评分最高的中档。任何想法如何做到这一点?

> 更新

另外两个表:

CREATE TABLE User(
    id INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
    username VARCHAR(50) UNIQUE NOT NULL,
    passwordhash VARCHAR(100) NOT NULL,
    fullname VARCHAR(50) NOT NULL,
    birthday DATE NOT NULL,
    joindate DATE NOT NULL,
    email VARCHAR(50) NOT NULL,
    picturepath VARCHAR(256) NOT NULL,
    favouritemovie VARCHAR(50) NOT NULL,
    favouritecategory INTEGER REFERENCES category(id),
    isDeleted BOOLEAN NOT NULL
);

CREATE TABLE Movie
(
    movieId INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
    title VARCHAR(255) NOT NULL,
    moviePath VARCHAR(500) NOT NULL
);
4

3 回答 3

1

从您的评论中:

计算每个中间值的平均评分(使用 GROUP BY 中间值),然后选择最大值并返回中间值

所以第一步,计算每个中间值的平均值:

select mid, 
       avg(rating) as avg_rating
from rating
group by mid;

现在选择最大值:

select max(avg_rating)
from (
  select avg(rating) as avg_rating
  from rating
  group by mid
) as mar

现在结合这些:

select ar.mid, mar.max_avg
from (
    select mid, 
           avg(rating) as avg_rating
    from rating
    group by mid
  ) as ar
  join (
    select max(avg_rating) as max_avg
    from (
      select avg(rating) as avg_rating
      from rating
      group by mid
    ) as t
  ) as mar
  on ar.avg_rating = mar.max_avg;

SQLFiddle 示例(使用 Postgres,但也适用于 HSQLDB):http ://sqlfiddle.com/#!12/e208a/8

这不是最简单的解决方案,但查询分组数据从来都不是。使用TOPLuther 所示的构造会快得多。唯一的缺点TOP 1是您不会注意到两部电影是否具有相同的平均评分。

编辑:只是为了在 HSQLDB 之外扩展一点。在支持窗口函数的数据库(PostgreSQL、Oracle 等)中,这类问题非常简单:

select *
from (
  select mid, 
         avg(rating) as avg_rating,
         dense_rank() over (order by avg(rating) desc) as rnk
  from rating
  group by mid
) t
where rnk = 1;

特别容易找到第二高、第三高等等 ( where rnk = 2, where rnk = 3),使用这些嵌套查询确实很复杂 - 但使用方法时会更容易一些TOP/LIMIT

于 2013-01-12T09:29:25.460 回答
0

大概是这样的:

SELECT TOP 10
  mid,
  avg(cast(r.rating as float))
FROM Rating r
GROUP BY mid
ORDER BY avg(cast(r.rating as float)) DESC

您不需要将等级更改为浮点数,但我认为如果您的等级为 4 和 5,您可能希望平均值为 4.5,而不是四舍五入为整数。

于 2013-01-12T09:12:27.010 回答
0

你说你想从大多数平均评级中选择中频..请试试这个..

select max(x.avgr)
from (
  select r.mid, avg(r.rating) avgr
  from rating r
  group by r.mid
) as x;

或试试这个:在Sql Server中工作。

select Top 1 r.mid, avg(r.rating) as avgr
from rating r
group by r.mid
order by avgr desc
;

那些Top不起作用的 dbms 你可以limit 1改用..

    select r.mid, avg(r.rating) as avgr
    from rating r
    group by r.mid
    order by avgr desc Limit 1
    ;
于 2013-01-12T09:29:54.267 回答