SELECT t.title, Max(t.st)
FROM (SELECT title,
Avg(stars) AS st
FROM movie
JOIN rating USING(mid)
GROUP BY title)t;
This is my query which I am writing to get max values of AVG(stars)
and it's corresponding title. Max value is coming fine but facing trouble in title. I am not getting corresponding title.
Output of subquery is:
Avatar 4.0
E.T. 2.5
Gone with the Wind 3.0
Raiders of the Lost Ark 3.33333333333
Snow White 4.5
The Sound of Music 2.5
Output of whole query is wrong .
The Sound of Music 4.5
Expected /Correct output is
SnowWhite 4.5
Try this
select t.title,
t.st
from
(select title,
avg(stars) as st,rank() over(order by avg(stars) desc) as rSt
from movie
join rating using(mID)
group by title)t where t.rSt=1 ;
It is ranking movies in descending order first, then in outer query's where condition, movie with highest rank is being selected. Hope this helps :-)
You can try using correlated subquery
select *
from
(select title,
avg(stars) as st
from movie a
join rating b on a.mID=b.mID
group by title
)t where st in
(select max(st) from (select title,
avg(stars) as st
from movie a
join rating b on a.mID=b.mID
group by title
)t1 on t.title=t1.title)
You can use WHERE condition in your query. You can experiment with joins or just use subquery.
Select title, max(stars)
from table
where stars = (select max(stars) from table)
or
SELECT top 1 title
FROM table
ORDER BY Stars DESC
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.