我可以在 select 语句中使用别名吗?
Can I use aliases within a select statement?
我想写一个这样的声明
select 1 as one, 2 as two , one + two as three
但是 SQL 服务器无法计算出 one + two
是什么。
我可以用这种形式重写
SELECT x.one
,x.two
,x.one + x.two AS three
FROM (
SELECT 1 AS one
,2 AS two
) x
这给了我预期的输出。它只是有点混乱(在一个非人为的例子中更是如此)我也不确定这种事情对 SQL 服务器的内部结构有什么影响以及对执行速度有什么影响。
有更好的方法吗?
您不能在同一个 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
同样的规则适用于 WHERE
:Reference alias (calculated in SELECT) in WHERE clause
但通常情况下,如果您多次使用相同的表达式不会有什么坏处,sql 服务器优化器只会对其求值一次。所以你可以这样做:
SELECT 1 as one, 2 as two , 1 + 2 as three
您可以像这样非常简单地命名您的值:
SELECT
one, two, one + two as three
FROM (values(1,2)) x(one,two)
我想写一个这样的声明
select 1 as one, 2 as two , one + two as three
但是 SQL 服务器无法计算出 one + two
是什么。
我可以用这种形式重写
SELECT x.one
,x.two
,x.one + x.two AS three
FROM (
SELECT 1 AS one
,2 AS two
) x
这给了我预期的输出。它只是有点混乱(在一个非人为的例子中更是如此)我也不确定这种事情对 SQL 服务器的内部结构有什么影响以及对执行速度有什么影响。
有更好的方法吗?
您不能在同一个 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
同样的规则适用于 WHERE
:Reference alias (calculated in SELECT) in WHERE clause
但通常情况下,如果您多次使用相同的表达式不会有什么坏处,sql 服务器优化器只会对其求值一次。所以你可以这样做:
SELECT 1 as one, 2 as two , 1 + 2 as three
您可以像这样非常简单地命名您的值:
SELECT
one, two, one + two as three
FROM (values(1,2)) x(one,two)