Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL - Define a column and use it in the same query

Tags:

sql

sql-server

Can I define a new column and use it in the same query?

For example,

Select 
    student, age + 10 as trueage, 
    case when trueage < 25 then 'False' else 'True' end
From 
    class

Thank you in advance for helping!

like image 838
Keane Nguyen Avatar asked May 26 '26 14:05

Keane Nguyen


2 Answers

CROSS APPLY would be handy here. Here is a nice article showing many uses of it.

Select
    student
    ,trueage
    ,case when trueage < 25 then 'False' else 'True' end
From
    class
    CROSS APPLY
    (
        SELECT age + 10 as trueage
    ) AS CA

It is mostly useful when you have complex formulas with several levels, something like this:

Select
    student
    ,trueage
    ,AgeFlag
From
    class
    CROSS APPLY
    (
        SELECT age + 10 as trueage
    ) AS CA1
    CROSS APPLY
    (
        SELECT case when trueage < 25 then 'False' else 'True' end AS AgeFlag
    ) AS CA2
like image 77
Vladimir Baranov Avatar answered May 30 '26 03:05

Vladimir Baranov


If you consider using a subquery "same query" then yes.

select student,
       trueAge,
       case when trueAge < 25 then 'false' else 'true' end as someColumn
from ( 
    select student, age + 10 as trueAge
    from table
) thingy

There are likely other ways to do this as well, this is only one of them.

like image 41
Kritner Avatar answered May 30 '26 04:05

Kritner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!