姓を取得するには:
select lastname
from names n join
position p
on n.id = p.id
where firstname in ('ben', 'rob')
group by lastname
having count(distinct firstname) = 2 and
1+max(case when firstname = 'ben' then p.position end) = max(case when firstname = 'rob' then p.position end)
その後、次の方法で元のリストを取得できます。
select n.*, p.position
from names n join
position p
on n.id = p.id
where firstname in ('ben', 'rob') and
lastname in (select lastname
from names n join
position p
on n.id = p.id
where firstname in ('ben', 'rob')
group by lastname
having count(distinct firstname) = 2 and
1+max(case when firstname = 'ben' then p.position end) = max(case when firstname = 'rob' then p.position end)
)
次のクエリはあなたの質問に答えると思いますが、これは名前を 1 つの行に結合するという警告があります。
select nben.*, p.position, nrob.*, prob.position
from names nben join
positions p
on nben.id = p.id and
nben.firstname = 'ben' join
names nrob
on nrob.firstname = 'rob' and
nrob.lastname = nben.lastname join
positions prob
on nrob.id = prob.id and
p.position = prob.position - 1
また、これはテストされていません。