My table is:
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,
);
I want to select the mid with most average rating:
select avg(r.rating) from rating r
witch returns the average. I want to return the mid`s with the most average rating. Any ideas how to do that?
> UPDATE
the other two tables:
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
);
From your comments:
So first step, calculate average for each mid:
Now choose the maximum:
Now combine these:
SQLFiddle example (using Postgres, but works with HSQLDB as well): http://sqlfiddle.com/#!12/e208a/8
It’s not the most simple solution but quering on grouped data never is. Using the
TOPconstruct as shown by Luther is going to be much faster. The only drawback with theTOP 1is that you won’t notice if two movies have the same average rating.Edit: Just to expand a little bit beyond HSQLDB. In a database that supports window functions (PostgreSQL, Oracle and many others), this type of question is very easy:
It is especially easy to find the second highest, third highest and so on (
where rnk = 2,where rnk = 3) which is really complicated using those nested queries – but a lit bit easier when using theTOP/LIMITaproach.