this closely related previous question asked.
i have many-to-many relationship between post , location.
the join table called postlocations, , has nothing fk's. (locationid, postid)
i'm trying pull top post each location.
this query have (which given in answer previous question):
select pl.locationid, p.postid, p.uniqueuri, p.content, max(s.basescore) topscore dbo.postlocations pl inner join dbo.posts p on pl.postid = p.postid inner join dbo.reviews r on p.postid = r.postid inner join dbo.scores s on r.scoreid = s.scoreid group pl.locationid, p.postid, p.uniqueuri, p.content
but problem is, because postlocations have entries this:
locationid postid 1 213213 2 498324 1 230943
so above query returning locationid 1 twice, because has 2 records in join table. want 1 record per location - top post per locationid.
i've tried this:
select l.locationid, p.postid, p.uniqueuri, p.content, max(s.basescore) topscore dbo.postlocations pl inner join dbo.locations l on pl.locationid = l.locationid inner join dbo.posts p on pl.postid = p.postid inner join dbo.reviews r on p.postid = r.postid inner join dbo.scores s on r.scoreid = s.scoreid group l.locationid, p.postid, p.uniqueuri, p.content
same result - comes back:
locationid postid uniqueuri content topscore 1 213213 some-post pew pew 2.00 2 498324 anot-post blah bl 4.50 1 230943 sadjsa-as asijd 3.5
this should come back:
locationid postid uniqueuri content topscore 1 230943 sadjsa-as asijd 3.5 2 498324 anot-post blah bl 4.50
because locationid 1 has 2 posts, postid 230943 has highest score 1 returned.
any ideas on i'm missing?
if using sql server 2005 or later, can like:
with rankedlocations ( select pl.locationid , s.basescore , p.postid , p.uniqueuri , p.content , row_number() over( partition pl.locationid order s.basescore desc ) scorerank dbo.postlocations pl join dbo.posts p on p.postid = pl.postid join dbo.reviews r on r.postid = p.postid join dbo.scores s on s.scoreid = r.scoreid ) select locationid, basescore, postid, uniqueuri, content rankedlocations scorerank = 1
Comments
Post a Comment