计算列上的T-SQL列别名 - 无效的列名称

时间:2011-07-06 03:13:32

标签: sql tsql

我正在使用别名来引用计算列。这是我正在努力工作的实际代码的片段,用于计算相似性并返回相似性得分为3或更高的匹配。

select [FirstName], difference([FirstName], 'mitch') as similarity
from [Dev].[dbo].[Name]
where similarity > 2
order by similarity desc

错误:

Invalid column name 'similarity'.

由于相似性不是真正的专栏,我将如何使其发挥作用?

4 个答案:

答案 0 :(得分:37)

列别名和计算在查询的投影(SELECT)阶段执行,该阶段在选择(WHEREJOIN)阶段之后发生。因此,它们不能在WHERE子句或JOIN条件中引用,因为它们尚不存在。您可以将查询与SELECT子句一起用作子查询,也可以在WHERE子句中复制计算:

select * 

from
(select [FirstName], difference([FirstName], 'mitch') as similarity
from [Dev].[dbo].[Name]) src

where similarity > 2
order by similarity desc

select [FirstName], difference([FirstName], 'mitch') as similarity
from [Dev].[dbo].[Name]
where difference([FirstName], 'mitch') > 2
order by similarity desc

答案 1 :(得分:11)

所有答案都可以解决您的问题,但对于复杂的情况,您无法复制查询。

正确的方法是使用CROSS and APPLY

select [FirstName], similarity
from [Dev].[dbo].[Name]
cross apply
  (
     select similarity =
     difference([FirstName], 'mitch')  
  )computed_column
where similarity > 2
order by similarity desc

whit CROSS和APPLY您可以在查询的任何位置使用计算列

答案 2 :(得分:7)

尝试:

SELECT * 
  FROM (
        SELECT [FirstName], difference([FirstName], 'mitch') as similarity
            FROM [Dev].[dbo].[Name]
        ) a
WHERE similarity > 2
ORDER BY similarity desc

答案 3 :(得分:1)

select [FirstName], difference([FirstName], 'mitch') as similarity
from [Dev].[dbo].[Name]
where difference([FirstName], 'mitch') > 2
order by 2 desc

您无法在where子句

中引用列别名