2016-01-23 101 views
1

我知道有很多解決方案,但不幸的是我無法使用分區或關鍵字TOP。沒有什麼我在早期的帖子上嘗試過。當前行爲NULL時選擇最後一個非NULL值

我的表看起來像這樣:

enter image description here

我想要的結果是,當所有的完成率是NULL它應該從最後一個非值完成百分比值,如:

enter image description here

我試過這個查詢,但沒有任何效果。你能告訴我我要去哪裏嗎?

SELECT sequence,project_for_lookup, 
CASE WHEN completion_percentage IS NOT NULL THEN completion_percentage 
ELSE 
    (SELECT max(completion_percentage) FROM [project_completion_percentage] AS t2 
    WHERE t1.project_for_lookup=t2.project_for_lookup and 
      t1.sequence<t2.sequence and 
      t2.completion_percentage IS NOT null 

END 

FROM [project_completion_percentage] AS t1 

回答

1

SQL Server 2008不支持累積窗口函數。所以,我建議outer apply

select cp.projectname, cp.sequence, 
     coalesce(cp.completion_percentage, cp2.completion_percentage) as completion_percentage 
from completion_percentage cp outer apply 
    (select top 1 cp2.* 
     from completion_percentage cp2 
     where cp2.projectname = cp.projectname and 
      cp2.sequence < cp.sequence and 
      cp2.completion_percentage is not null 
    order by cp2.sequence desc 
    ) cp2; 
+0

我不能使用關鍵字TOP或外部應用。它給出了錯誤 –

+0

發現了OUTER,但預期的表達結束 –

+0

@NishaNethani。 。 。然後我會得出結論,您沒有使用SQL Server 2008,如您問題上的標記所示。 –

0

這是行嗎?這對我來說似乎是。您錯過了一個括號並且序列向後。

http://sqlfiddle.com/#!3/465f2/4

SELECT sequence,project_for_lookup, 
CASE WHEN completion_percentage IS NOT NULL THEN completion_percentage 
ELSE 
    (
     SELECT max(completion_percentage) 
     FROM [project_completion_percentage] AS t2 
     WHERE t1.project_for_lookup=t2.project_for_lookup 

      -- sequence was reversed. You're on the row t1, and want t2 that is from a prior sequence. 
      and t2.sequence<t1.sequence 
      and t2.completion_percentage IS NOT null 

    --missing a closing paren 
    ) 
END 

FROM [project_completion_percentage] AS t1 
相關問題