替换sql server 2008中的First_Value()

时间:2013-12-04 14:23:03

标签: sql sql-server sql-server-2008

我有以下查询在Oracle和DB2中运行良好。但它在SQL Server 2008中不起作用,因为First_Value函数不可用。是否有适合2008年的工作?

select NameGuid, Name, AncestorGuid, ProductGuid, PathLength
from (
    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
    from ( 
        ... your original query ...
    )
)
where 
-- return rows whose NameGuid is the same as the NameGuid calculated by first_value(...)
NameGuid = MinNameGuid

注意:该查询是对我之前的post

的回答

1 个答案:

答案 0 :(得分:0)

您可以在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 DEMO