2

我有以下查询:

    select FirstName, LastName,
    Case
     When LastName = 'Jones'
     then 'N/A'
    End as Other,
    Case 
      When Other is not null 
      then 1 
    else 0 as Flag

Flag 值取决于 Other,但由于 Other 是别名,因此 Flag 字段无法识别 Other。

我想,我可以在选择中使用选择。Flag 是否有更好的方法来识别其他别名列?

4

3 回答 3

5

由于解析查询的方式,您不能引用 SELECT 和 ORDER BY 之外的别名。典型的解决方法是将其埋在派生表中:

SELECT 
  FirstName, LastName, Other, 
  Flag = CASE WHEN Other IS NOT NULL THEN 1 ELSE 0 END
FROM 
(
  SELECT FirstName, LastName,
    CASE WHEN LastName = 'Jones'
     THEN 'N/A'
    END AS Other
  FROM dbo.table_name
) AS x;
于 2012-08-15T19:21:52.313 回答
1

您也可以使用公用表表达式 (CTE) 执行此操作:

;WITH cte AS 
(
SELECT 
    firstname, 
    lastname, 
    CASE WHEN lastname = 'Jones' THEN 'N/A' 
    END AS Other 
FROM @t
) 
SELECT 
    firstname, 
    lastname, 
    CASE WHEN other IS NOT NULL THEN 1 
        ELSE 0 
    END AS Flag 
FROM cte
于 2012-08-15T19:41:25.723 回答
0

您必须SELECT在 a 中使用 a SELECT

SELECT FirstName, LastName, Other, 
    Case When Other is not null 
         then 1 
         else 0 END as Flag
FROM 
(
    select FirstName, LastName,
        Case
         When LastName = 'Jones'
         then 'N/A'
        End as Other
    from yourTable
) x

或者,您可以在评估字段时重用该字段的CASE语句:OtherFlag

select FirstName, 
    LastName,
    Case 
        When LastName = 'Jones'
        then 'N/A'
    End as Other,
    case when LastName = 'Jones' -- your Other CASE code here
        then 1
        else 0
    END as flag 
from yourTable
于 2012-08-15T19:27:10.310 回答