2017-06-28 19 views
0

在视图中,我将一个select语句放在一个案例中,并将其作为列进行了扩展。列名是'IR2'使用Microsoft SQL在创建的列上创建案例表达式

我该如何关闭“IR2”列?

我最终得到一个错误,说'无效列名'IR2'。

我的选择是什么?

case when r.ana = 'nh3' and r.serv='energy' and exists(select 1 from results x where x.no=r.no and x.ana='nh3' and x.sa='rejected' and x.serv <> 'energy') 
then '*' else r.sa end as IR2, 

CASE IR2 WHEN 'Released' then 
'' 
ELSE 
'*' 
END AS IR 
+0

您不能在select子句中使用别名IR2 – sle1306

回答

1

CTE将是最好的选择。如果您想继续使用当前的声明,则需要在其他案例声明中添加案例声明的副本。非常混乱的代码。

SELECT 
case when r.ana = 'nh3' and r.serv='energy' and 
exists(select 1 from results x where x.no=r.no and x.ana='nh3' and x.sa='rejected' and x.serv <> 'energy') 
then '*' else r.sa end as IR2, 

CASE 
    (case when r.ana = 'nh3' and r.serv='energy' 
     and exists(select 1 from results x where x.no=r.no and x.ana='nh3' and x.sa='rejected' and x.serv <> 'energy') 
     then '*' else r.sa end) 
WHEN 'Released' then 
    '' 
ELSE 
    '*' 
END AS IR 
2

您可以使用子查询或CTE。但在SQL Server的另一有趣的方式是使用outer apply

select v.IR2, 
     (case IR2 when 'Released' then '' else '*' end) as ir 
from . . . outer apply 
    (values (case when r.ana = 'nh3' and r.serv='energy' and 
         exists(select 1 from results x where x.no=r.no and x.ana='nh3' and x.sa='rejected' and x.serv <> 'energy') 
        then '*' else r.sa 
       end) 
    ) v(IR2) 
+2

IR2不是字段而是查询中的别名。该别名只能用在'order by'子句中,而不能在select中的其他地方使用。 – sle1306

+0

@ sle1306。 。 。咦?在'FROM'子句中使用'OUTER APPLY'定义'IR2'。你的评论是错误的,为什么它会得到upvoted我不知道。 –

+0

我正在考虑问题中的原始查询,而不是您答案中的问题。 – sle1306