2016-01-23 105 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 
相关问题