您可以在 SQL Server 2008 中尝试复制First_Value
功能
;with CTE(NameGuid, Name, AncestorGuid, ProductGuid, PathLength) AS
(
select
NameGuid,
Name,
AncestorGuid,
ProductGuid,
PathLength,
-- take every row from original query with the same Name as this,
-- order those rows by PathLength (and NameGuid to disambiguate)
-- and return the NameGuid of the first row in that "partition"
-- first_value(NameGuid) over (partition by Name order by PathLength asc, NameGuid asc) MinNameGuid
ROW_NUMBER() over (partition by Name order by PathLength asc, NameGuid asc) MinNameGuid
from (
... your original query ...
)a
)
Select c.NameGuid, c.Name, c.AncestorGuid, c.ProductGuid,
c.PathLength,c1.NameGUID
from CTE c
LEFT JOIN
(SELECT NAMEGUID,Name from CTE where MinNameGuid = 1) C1
on
c.Name = C1.Name
where c1.NAMEGUID is not NULL
SQL FIDDLE 演示 http://sqlfiddle.com/#!6/3186d/9