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
这是结果
"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"
我想要的是评分最高的嘉宾PER SHOW,所以它应该有5条记录,每条可用的节目中有一条最高评价的客人记录
答案 0 :(得分:3)
这是row_number()
函数的一个很好的应用:
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;
我还修改了代码以使用显式join
语法。
如果您希望每个节目有五位嘉宾,请使用seqnum <= 5
。
答案 1 :(得分:1)
如果每场演出只需要一位嘉宾 - 您可以使用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