我希望以下列方式获取数据
运行查询我应该得到以下ID 2,3,4,6。 我会得到Id 6但不是Id 1,因为1是6和5的父级,因为6有最大版本,所以第6行会被选中。
答案 0 :(得分:0)
创建了我自己的样本数据,因为图像不可用。您需要根据自己的数据进行调整。这应该可以让你获得你所追求的,但是:
{{1}}
答案 1 :(得分:0)
Create table #tmp (id int, [version] int, parent int)
insert into #tmp values(1,0,null)
insert into #tmp values(2,0,null)
insert into #tmp values(3,0,null)
insert into #tmp values(4,0,null)
insert into #tmp values(5,0,1)
insert into #tmp values(6,1,1)
--insert into #tmp values(7,2,1)
--insert into #tmp values(8,2,2)
--insert into #tmp values(9,3,2)
--SElect * from #tmp
SELECT id, version, parent
FROM(
SELECT *, ROW_NUMBER()OVER(PARTITION BY parent ORDER BY version DESC) rn
FROM #tmp
)X
WHERE ((rn = 1 and parent is not null) or (parent is null))
AND id not in (SELECT DISTINCT Parent From #tmp where Parent is not null )
DRop table #tmp