如何在同一个select语句中使用条件列值?

时间:2011-04-26 12:57:01

标签: sql-server sql-server-2008 case conditional-statements

我有类似

的东西

COMPLEX_EXPRESSION_N代表一个长子查询)

select
  ID_Operation,
  FirstCheck = CASE WHEN (COMPLEX_EXPRESSION_1)= 0 then 0 else 1 end,
  SecondCheck = CASE WHEN (COMPLEX_EXPRESSION_2)= 0 then 0 else 1 end,
  ThirdCheck = CASE WHEN (COMPLEX_EXPRESSION_3)= 0 then 0 else 1 end,
  AllChecksOk = Case WHEN 
               (FirstCheck + SecondCheck + Third CHeck = 3) 
               Then 'OK' Else 'No' End
from 
  AllOperationsTable

是否可以像在AllChecksOk系列中那样使用FirstCheck,SecondCheck,ThirdCheck?

我不关心性能,这是每天在极少数记录上手动运行的东西,我只是想避免创建视图,表或临时表并将所有内容保存在单个select语句中。

作为一种有效的方法,我可以这样做,但它使查询的可读性降低(因为我需要为每个复杂的表达式编写两次):

select
  ID_Operation,
  FirstCheck = CASE WHEN (COMPLEX_EXPRESSION_1)= 0 then 0 else 1 end,
  SecondCheck = CASE WHEN (COMPLEX_EXPRESSION_2)= 0 then 0 else 1 end,
  ThirdCheck = CASE WHEN (COMPLEX_EXPRESSION_3)= 0 then 0 else 1 end,
  AllChecksOk = Case WHEN 
               (COMPLEX_EXPRESSION_1+ COMPLEX_EXPRESSION_2+ 
               COMPLEX_EXPRESSION_3CHeck = 3) Then 'OK' Else 'No' End
from 
  AllOperationsTable

2 个答案:

答案 0 :(得分:4)

您无法在select中引用列别名,但您可以使用以下CTE。

;WITH CTE AS
(
select
  ID_Operation,
  FirstCheck = CASE WHEN (COMPLEX_EXPRESSION_1)= 0 then 0 else 1 end,
  SecondCheck = CASE WHEN (COMPLEX_EXPRESSION_2)= 0 then 0 else 1 end,
  ThirdCheck = CASE WHEN (COMPLEX_EXPRESSION_3)= 0 then 0 else 1 end
from 
  AllOperationsTable
)
SELECT *,
       AllChecksOk = Case WHEN 
               (COMPLEX_EXPRESSION_1+ COMPLEX_EXPRESSION_2+ 
               COMPLEX_EXPRESSION_3CHeck = 3) Then 'OK' Else 'No' End
FROM CTE

您还可以使用CROSS APPLY定义3列别名,然后在主SELECT列表as in this example中引用它们。

答案 1 :(得分:3)

以下是派生表解决方案

SELECT
  T.ID_Operation,
  FirstCheck   = CASE WHEN T.Expr1 = 0 THEN 0 ELSE 1 END,
  SecondCheck  = CASE WHEN T.Expr2 = 0 THEN 0 ELSE 1 END,
  ThirdCheck   = CASE WHEN T.Expr3 = 0 THEN 0 ELSE 1 END,
  AllChecksOk  = CASE WHEN T.Expr1 + T.Expr2 + T.Expr3 = 3 THEN 'OK' ELSE 'No' END
FROM
(
  SELECT
    ID_Operation,
    Expr1 = (COMPLEX_EXPRESSION_1),
    Expr2 = (COMPLEX_EXPRESSION_2),
    Expr3 = (COMPLEX_EXPRESSION_3)
  FROM 
    AllOperationsTable
) T