Question

set search_path = 'project';

select g.firstname,g.lastname, g.rating, sh.showname
from guest g, shows sh, timeslot ts
where sh.shownumber = ts.shownumber
and ts.guestnumber = g.guestnumber 
order by sh.showname

this is the result

"Charlie ";"Sheen";7.2;"Cooking Show"
"Charlie";"Sheen";7.2;"Cooking Show"
"Carl";"Makky";7.0;"Cooking Show"
"Barack";"Obama";6.7;"Fitness Mania"
"Vladimir";"Putin";8.2;"Fitness Mania"
"kim";"jung";5.3;"Fitness Mania"
"kim";"jung";5.3;"Gamers Heaven"
"Justin";"Trudeau";8.5;"Kids Play Time"
"Charlie";"Sheen";7.2;"Kids Play Time"
"ellen";"page";9.2;"Weather News"

What I want is the highest rated guest PER SHOW, so it should have 5 records, one record of each available show with the highest rating guest

Was it helpful?

Solution 2

If you need only one guest per show - you can use DISTINCT ON:

select distinct on (sh.showname) g.firstname, g.lastname, g.rating, sh.showname
from guest g, shows sh, timeslot ts
where sh.shownumber = ts.shownumber
and ts.guestnumber = g.guestnumber 
order by sh.showname, g.rating desc

OTHER TIPS

This is a good application of the row_number() function:

select firstname, lastname, rating, showname
from (select g.firstname, g.lastname, g.rating, sh.showname,
             row_number() over (partition by sh.showname order by g.rating desc) as seqnum
      from guest g shows sh join
           timeslot ts
           on sh.shownumber = ts.shownumber join
           guest g
           on ts.guestnumber = g.guestnumber  
     ) gr
where seqnum = 1
order by showname;

I also modified the code to use explicit join syntax.

If you want five guests per show, use seqnum <= 5.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top