这得到二哥使用 OUTER APPLY:
select m.*, elder.*
from Member m
outer apply
(
select top 2 ElderBirthDate = x.BirthDate, ElderFirstname = x.Firstname
from Member x
where x.BirthDate < m.BirthDate
order by x.BirthDate desc
) as elder
order by m.BirthDate, elder.ElderBirthDate desc
源数据:
create table Member
(
Firstname varchar(20) not null,
Lastname varchar(20) not null,
BirthDate date not null unique
);
insert into Member(Firstname,Lastname,Birthdate) values
('John','Lennon','Oct 9, 1940'),
('Paul','McCartney','June 8, 1942'),
('George','Harrison','February 25, 1943'),
('Ringo','Starr','July 7, 1940');
输出:
Firstname Lastname BirthDate ElderBirthDate ElderFirstname
-------------------- -------------------- ---------- -------------- --------------------
Ringo Starr 1940-07-07 NULL NULL
John Lennon 1940-10-09 1940-07-07 Ringo
Paul McCartney 1942-06-08 1940-10-09 John
Paul McCartney 1942-06-08 1940-07-07 Ringo
George Harrison 1943-02-25 1942-06-08 Paul
George Harrison 1943-02-25 1940-10-09 John
(6 row(s) affected)
现场测试:http ://www.sqlfiddle.com/#!3/19a63/2
marc 的答案更好,如果您需要向主实体查询“近”实体(例如地理空间、哥哥、最接近到期日等),只需使用 OUTER APPLY 即可。
外部应用演练:http ://www.ienablemuch.com/2012/04/outer-apply-walkthrough.html
不过,您可能需要 DENSE_RANK 而不是 ROW_NUMBER/RANK,因为评论的最高标准可能会产生平局。TOP 1 可以产生超过 1 个,TOP 3 也可以产生超过 3 个。该场景的示例(DENSE_RANK 演练):http ://www.anicehumble.com/2012/03/postgresql-denserank.html