22,209
社区成员
发帖
与我相关
我的任务
分享
create table TableA(id int)
insert into TableA
select 1 union all
select 2 union all
select 3
create table TableB(id int,ParentID int)
insert into TableB
select 1, 1 union all
select 2, 2 union all
select 3, 2 union all
select 4, 3 union all
select 5, 3 union all
select 6, 3
select a.id,b.id 'ParentID'
from TableA a
inner join
(select row_number() over(partition by ParentID order by getdate()) rn,
id,ParentID from TableB) b
on a.id=b.ParentID and b.rn=1
id ParentID
----------- -----------
1 1
2 2
3 4
(3 row(s) affected)
select a.*,b.* from TableA a inner join tableB b on a.id=b.parentid where not exists(select 1 from TableB where ParentID = b.ParentID and id<b.id)
select * from TableB a where not exists(select 1 from TableB where ParentID = a.ParentID and id<a.id)