SQL - 定义列并在同一查询中使用它

时间:2021-06-06 15:45:18

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!

提前感谢您的帮助!

3 个解决方案

#1


3  

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

#2


0  

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.

可能还有其他方法可以做到这一点,这只是其中之一。

#3


0  

Something like:

就像是:

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

#1


3  

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

#2


0  

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.

可能还有其他方法可以做到这一点,这只是其中之一。

#3


0  

Something like:

就像是:

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