简体   繁体   中英

Alternate for First_Value() in sql server 2008

I have the following query that works well in Oracle and DB2 . But it does not work in SQL Server 2008 because First_Value function is not available with the same . Is there a work around for 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

Note : The query was an answer to my previous post

You can try this in SQL Server 2008 to replicate First_Value function

;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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM