In my select statement there is a CASE WHEN THEN ELSE END AS statement that I am not able to filter on in my WHERE clause. I do not see why this would be an issue, could someone shed some light?
SELECT
CASE
WHEN m.Country IN ('CANADA', 'UNITED STATES', 'USA', 'MEXICO') THEN 'NA'
WHEN m.Country IN ('BRAZIL') THEN 'JD2'
WHEN m.Country IN ('NZ', 'NEW ZEALAND', 'AUSTRALIA', 'AUSTRALASIA') THEN 'ANZ'
ELSE 'Unknown'
END AS DerivedRegion,
m.ID,
m.[Account Name],
m.[Display Name],
m.[Last Name],
m.[First Name]
FROM dbo.Users AS m
WHERE DerivedRegion = 'Unknown'
There WHERE clause gives me the error: Invalid column name 'DerivedRegion', why?
CASE statements allow you to categorize data that you're interested in -- and exclude data you're not interested in. In order to do this, you can use a CASE statement as a filter in the WHERE statement to remove output you don't want to see.
Another way to use the Case Statement is within the WHERE clause. There, it may be utilized to alter the data fetched by a query based on a condition. Within that context, the Case Statement is ideally suited to both static queries, as well as dynamic ones, such as those that you would find inside a stored procedure.
You can use a CASE Statement anywhere a valid expression is used within the SELECT statement such as the WHERE clause's filter criteria.
The WHERE clause is used to filter records. It is used to extract only those records that fulfill a specified condition.
WHERE
is processed before SELECT
. It doesn't know what DerviedRegion
is at that point. I'd recommend using a NOT IN
in this case to exclude the list of countries. However, if you really want to use your CASE you could do something like this
SELECT *
FROM
(
SELECT
CASE
WHEN m.Country IN ('CANADA', 'UNITED STATES', 'USA', 'MEXICO') THEN 'NA'
WHEN m.Country IN ('BRAZIL') THEN 'JD2'
WHEN m.Country IN ('NZ', 'NEW ZEALAND', 'AUSTRALIA', 'AUSTRALASIA') THEN 'ANZ'
ELSE 'Unknown'
END AS DerivedRegion,
m.ID,
m.[Account Name],
m.[Display Name],
m.[Last Name],
m.[First Name]
FROM dbo.Users AS m
) AS x
WHERE x.DerivedRegion = 'Unknown'
Check out MSDN and scroll down to Logical Processing Order of the SELECT statement to see the order in which a query is processed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With