Dies ist eng verwandt mit einer vorherigen Frage, die ich gestellt habe.T-SQL - Hilfe mit MAX-Operation über Viele-zu-Viele
Ich habe eine many-to-many Beziehung zwischen Beitrag und Ort.
Die Join-Tabelle heißt PostLocations und hat nichts außer den FK's. (LocationId, PostId)
Ich versuche, die oberen Pfosten für jeden Standort zurückzuziehen.
Dies ist die Abfrage Ich habe (die in der Antwort auf meine vorherige Frage gegeben wurde):
SELECT pl.LocationId, p.postid, p.UniqueUri, p.Content, MAX(s.BaseScore) as topscore
from 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 by pl.locationid, p.postid, p.UniqueUri, p.Content
Aber das Problem ist, weil PostLocations Einträge wie diese haben könnte:
LocationId PostId
1 213213
2 498324
1 230943
Also meine obige Abfrage gibt LocationId 1 zweimal zurück, weil es zwei Datensätze in der Join-Tabelle hat. Ich möchte nur 1 Datensatz pro Standort - der oberste Beitrag pro Locationid.
Ich habe auch versucht, dies:
SELECT l.LocationId, p.postid, p.UniqueUri, p.Content, MAX(s.BaseScore) as topscore
from 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 by l.locationid, p.postid, p.UniqueUri, p.Content
Gleiches Ergebnis - das ist, was zurückkommt:
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 a 3.5
Dies ist, was sollte kommen zurück:
LocationId PostId UniqueUri Content TopScore
1 230943 sadjsa-as asijd a 3.5
2 498324 anot-post blah bl 4.50
Da LocationId 1 über 2 Posts verfügt, hat PostId 230943 die höchste Punktzahl, sodass i Der eine ist zurückgekehrt.
Irgendwelche Ideen zu was ich vermisse?
Ahh ROW_NUMBER()! Natürlich..ich benutze es überall, nur habe ich nicht gedacht, es hier zu benutzen. Funktioniert ein Charme - danke! – RPM1984
+1 viel sauberer als meins, ich habe nie in Erwägung gezogen mit row_number() Zu viel Zeit mit sqlserver 2000 zu arbeiten lässt mich vergessen, dass es existiert – Robb
@Robb - * GENAU * das gleiche Szenario für mich. von 5 Jahren meines Programmierlebens verwendeten 4 von ihnen SQL2000. Welt des Schmerzes. – RPM1984