2017-08-10 85 views
1

我有如下表:獲取以前行的值(不工作SQL Server 2008上LAG)


Query ID No_ Name  Value   Description 
    3  PP120 C1   0   NULL 
    2  PP121 NULL  140   Positive 
    3  PP122 C1   0   NULL 
    3  PP123 C1   0   NULL 
    3  PP124 C1   0   NULL 
    3  PP125 C1   0   NULL 
    2  PP126 NULL  170   Positive 
    2  PP127 NULL  -658   Positive 
    2  PP128 NULL  547   Positive 
    3  PP129 C1   0   NULL 
    3  PP130 C1   0   NULL 
    3  PP131 C1   0   NULL 

這是兩個不同的查詢的聯合的結果(見ID查詢) :

SELECT [Query ID]=2, SL.[No_], CL.[Name] ,SL.Value, SL.Type 
FROM SLine SL 
LEFT JOIN CLine CL ON SL.[No_] = CL.[No_]  
WHERE 
SL.[Type] <> '' 

UNION 

SELECT [Query ID]=3, SL.[No_], CL.[Name] ,SL.Value, SL.Type 
FROM SLine] SL 
LEFT JOIN CLine CL ON SL.[No_] = CL.[No_] 
WHERE 
SL.[Type] <> '' 

我需要用不同查詢ID上具有相同No_的值替換所有變量'name'。即我將需要:

Query ID No_ Name  Value  Description 
    3  PP120 C1   0   NULL 
    2  PP121 C1   140   Positive 
    3  PP122 C1   0   NULL 
    3  PP123 C1   0   NULL 
    3  PP124 C1   0   NULL 
    3  PP125 C1   0   NULL 
    2  PP126 C1   170   Positive 
    2  PP127 C1   -658   Positive 
    2  PP128 C1  547   Positive 
    3  PP129 C1   0   NULL 
    3  PP130 C1   0   NULL 
    3  PP131 C1   0   NULL 

我給你提供的表只是12000行結果的一部分。我試圖向以下來獲得相同的名稱爲每個NO_但我需要使用SQL Server 2008,我不能使用下面的代碼:

SELECT  
CASE WHEN [Name] IS NULL THEN LEAD([Name], 1, 0) OVER 
(PARTITION BY [No_] ORDER BY [No_] ASC) AS [Name_], * FROM (

SELECT [Query ID]=3, SL.[No_], CL.[Name] ,SL.Value, SL.Type 
FROM SLine SL 
LEFT JOIN CLine CL ON SL.[No_] = CL.[No_]  
WHERE 
SL.[Type] <> '' 

UNION 

SELECT [Query ID]=2, SL.[No_], CL.[Name] ,SL.Value, SL.Type 
FROM SLine] SL 
LEFT JOIN CLine CL ON SL.[No_] = CL.[No_] 
WHERE 
SL.[Type] <> '' 
)V 

任何建議作爲替代落後的功能?

回答

3

使用CTE和ROW_NUMBER,然後自連接創建一個僞滯後/超前

With CTE as 
(
select Q1.*, row_number() over (order by [No_]) rn 
from MyQuery Q1 
) 
select C1.*, 
     case when c2.Column is null then C1.Column else c2.Column end as Pseudo_Lead 
from CTE c1 
left join CTE c2 
on c2.rn = c1.rn +1 
and <any other partition conditions> 
相關問題