I have the following query:
select FirstName, LastName,
Case
When LastName = \'Jones\'
then \'N/A\'
End as Other,
Case
When
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
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
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;