I want to combine
Select top 2 scouting.*
From scouting
Where scouting.astroLoc Like 'D01%' AND scouting.ownerGuild = 'SWARM'
Order By scouting.jumpGate Desc
with
Select top 2 scouting.*
From scouting
Where scouting.astroLoc Like 'D02%' scouting.ownerGuild = 'SWARM'
Order By scouting.jumpGate Desc
with
Select top 2 scouting.*
From scouting
Where scouting.astroLoc Like 'D03%' scouting.ownerGuild = 'SWARM'
Order By scouting.jumpGate Desc
continued until
Select top 2 scouting.*
From scouting
Where scouting.astroLoc Like 'D79%' scouting.ownerGuild = 'SWARM'
Order By scouting.jumpGate Desc
… into 1 SQL query whereby the TOP 3 records are grouped by scouting.astroLoc ascending.
This is the “greatest-n-per-group” problem that is posted frequently on StackOverflow. Here’s a solution:
This works because the query tries to match a given row
s1to the set of rowss2that have the sameastroLocand a greaterjumpGatevalue. TheHAVINGclause restricts the result tos1rows that match fewer than two, which means that the row would be in the top 2.This assumes rows are unique over [
astroLoc,jumpGate]. If not, you may need to add another term to the join condition to resolve ties.Re your comment, try the following alteration:
This compares only the first three characters of
astroLocfor purposes of testing a row is in the same “group” as the other, and it also resolves ties injumpGateby using the primary key.Re your other answer with new requirements:
It’s hard to follow what you’re asking for, since I don’t know what are your table definitions or the meanings of columns. Do you want the outer query to be matched to the top three jumpgates that are owned by the SWARM guild?
That would be a different query from this one, which makes the outer query return the jumpgates owned by SWARM that match the top three jumpgates owned by anyone.
It’s possible the second query will return an empty result, if none of the SWARM jumpgates are in the top three.
PS: It’s customary on StackOverflow to edit your original question post at the top, when you need to add more detail or followup questions.