[英]T-SQL Column alias on computed column - Invalid column name
I'm using an alias to refer to a computed column.我使用别名来引用计算列。 Here is a snippet from the actual code I'm trying to make work, to compute similarity and return matches where the similarity score is 3 or higher.
这是我正在尝试制作的实际代码的片段,用于计算相似度并返回相似度得分为 3 或更高的匹配项。
select [FirstName], difference([FirstName], 'mitch') as similarity
from [Dev].[dbo].[Name]
where similarity > 2
order by similarity desc
Exception Message:异常消息:
Invalid column name 'similarity'.
列名“相似性”无效。
As similarity is not a real column, how would I make this work?由于相似性不是真正的专栏,我将如何进行这项工作?
Column aliases and computations are performed in the projection ( SELECT
) phase of the query, which occurs after the selection ( WHERE
and JOIN
) phase.列别名和计算在查询的投影(
SELECT
)阶段执行,该阶段发生在选择( WHERE
和JOIN
)阶段之后。 Because of this, they can't be referenced in the WHERE
clause or in a JOIN
condition because they do not yet exist.因此,它们不能在
WHERE
子句或JOIN
条件中引用,因为它们尚不存在。 You can either use your query with the SELECT
clause as a subquery or you can duplicate the computation in the WHERE
clause:您可以将查询与
SELECT
子句一起用作子查询,也可以在WHERE
子句中复制计算:
select *
from
(select [FirstName], difference([FirstName], 'mitch') as similarity
from [Dev].[dbo].[Name]) src
where similarity > 2
order by similarity desc
or或者
select [FirstName], difference([FirstName], 'mitch') as similarity
from [Dev].[dbo].[Name]
where difference([FirstName], 'mitch') > 2
order by similarity desc
All answers can solve your problem but for complicated situation you just can't duplicate your query.所有答案都可以解决您的问题,但对于复杂的情况,您无法复制您的查询。
The correct way is by using CROSS and APPLY正确的方法是使用CROSS 和 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 and APPLY you can use your computed column everywhere on the query whit CROSS 和 APPLY 你可以在查询的任何地方使用你的计算列
Try:尝试:
SELECT *
FROM (
SELECT [FirstName], difference([FirstName], 'mitch') as similarity
FROM [Dev].[dbo].[Name]
) a
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 2 desc
You can't reference column aliases in where clause您不能在 where 子句中引用列别名
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.