Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TSQL - Use a Derived Select Column in the Where Clause

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").

like image 606
Greg Avatar asked Jan 19 '10 20:01

Greg


People also ask

Can we use select statement in WHERE clause?

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.

How do I add a derived column in SQL?

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.

How do you use WHERE in select?

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.

What is a derived column in SQL?

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.


1 Answers

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
like image 96
A-K Avatar answered Nov 02 '22 23:11

A-K