我可以在select语句中使用别名吗?

时间:2015-03-25 12:58:25

标签: sql sql-server sql-optimization

我想写一个看起来像这样的声明

select 1 as one, 2 as two , one + two as three

但是,SQL Server无法确定one + two是什么。

我可以用这种形式重写

SELECT x.one
      ,x.two
      ,x.one + x.two AS three
FROM (
    SELECT 1 AS one
          ,2 AS two
    ) x

这给了我期望的输出。它只是有点混乱(在一个非人为的例子中更是如此)我也不确定这类事情对SQL Server的内部做了什么以及对执行速度有何影响。

有更好的方法吗?

2 个答案:

答案 0 :(得分:4)

您无法在同一SELECT中引用别名,您需要在子查询中定义(如您所做)或在Common-table-expression(CTE)中定义:

WITH CTE AS
(
    SELECT 1 as one, 2 as two
)
SELECT one, two, one + two AS three FROM CTE

或者使用以下语法:

WITH CTE(one, two) AS
(
    SELECT 1, 2
)
SELECT one, two, one + two as three from CTE

同样的规则适用于WHEREReference alias (calculated in SELECT) in WHERE clause

但是,如果多次使用相同的表达式通常不会造成伤害,sql server优化器只会对它进行一次评估。所以你可以这样做:

SELECT 1 as one, 2 as two , 1 + 2 as three

答案 1 :(得分:1)

您可以非常简单地命名您的值:

SELECT 
  one, two, one + two as three
FROM (values(1,2)) x(one,two)