Is there a way in TSQL to do something like this:
select a,b,c,
case
when a=1 then 5
when a=2 then 6
end as d
from some_table
where d=6
The actual case statement is really complex, so I'm trying to avoid repeating it in the where clause? Are there any tricks to do this?
(I think there's a trick in MySQL to use "having d=6").
You should use the WHERE clause to filter the records and fetching only the necessary records. The WHERE clause is not only used in the SELECT statement, but it is also used in the UPDATE, DELETE statement, etc., which we would examine in the subsequent chapters.
Use SQL Server Management Studio In Object Explorer, expand the table for which you want to add the new computed column. Right-click Columns and select New Column.
WHERE clause Syntax. The basic syntax for the WHERE clause when used in a MySQL SELECT WHERE statement is as follows. “WHERE” is the keyword that restricts our select query result set and “condition” is the filter to be applied on the results. The filter could be a range, single value or sub query.
Derived columns let you move the processing of an expression from the target instance to the source instance. For example, you may have already defined an expression that concatenates the values of two source columns, FIRSTNAME and LASTNAME, and mapped this expression to a target column named called FULLNAME.
select
a, b, c
from (
select
a, b, c,
case
when a=1 then 5
when a=2 then 6
end as d
from some_table
) as t
where d=6
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