2

I have the following query:

    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

The Flag value depends on Other but as Other is an alias, the Flag field does not recognize Other.

I guess, I can use a select within a select. Is there a better way for Flag to recognize the Other alias column?

Aaron Bertrand
  • 272,866
  • 37
  • 466
  • 490
Nate Pet
  • 44,246
  • 124
  • 269
  • 414

3 Answers3

5

You can't refer to an alias outside of SELECT and ORDER BY because of the way a query is parsed. Typical workaround is to bury it in a derived table:

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;
Aaron Bertrand
  • 272,866
  • 37
  • 466
  • 490
1

You can also do this with a common table expression (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
wBob
  • 13,710
  • 3
  • 20
  • 37
0

You will have to use a SELECT in 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

Or you can reuse the CASE statement for the Other field when evaluating the Flag field:

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
Taryn
  • 242,637
  • 56
  • 362
  • 405