在WHERE子句中重用计算列

时间:2017-01-17 09:13:20

标签: sql sql-server tsql

在SELECT语句中,我想重用WHERE子句中的计算列。有没有办法在SQLserver中这样做?

简化示例:

工作,但重复计算:

SELECT field1, concat(field2, field3) AS calc_field
  FROM MyTable
  WHERE concat(field2, field3) LIKE 'A%'

所需

SELECT field1, concat(field2, field3) AS calc_field
  FROM MyTable
  WHERE calc_field LIKE 'A%'

5 个答案:

答案 0 :(得分:6)

无法在同一级别SELECT上重复使用计算字段。您需要将其嵌套才能使用别名。

SELECT field1
    , calc_field
FROM (
    SELECT field1
        , CONCAT (field2, field3) AS calc_field
    FROM MyTable
    ) tbl
WHERE calc_field LIKE 'A%'

This is because of the order in which clauses are executed in a SQL query。正如您在列出子句的方式中所看到的,生成别名的SELECT子句在WHERE子句之后执行。

因此,别名在WHERE子句中不是“可见的”,因为别名是在应用WHERE之后生成的。

答案 1 :(得分:4)

现有答案的另一个变体是使用公用表表达式(CTE):

WITH cte AS (
    SELECT field1, concat(field2, field3) AS calc_field
    FROM mytable
)
SELECT field1, calc_field
FROM cte
WHERE calc_field LIKE 'A%'

您也可以滥用CROSS APPLY

SELECT field1, ca.calc_field
FROM MyTable
CROSS APPLY (
    SELECT concat(field2, field3) AS calc_field
) AS ca
WHERE ca.calc_field LIKE 'A%';

答案 2 :(得分:3)

将其包装在派生表中:

select field1, calc_field
from
(
    SELECT field1, concat(field2, field3) AS calc_field
    FROM MyTable
) dt
WHERE calc_field LIKE 'A%'

答案 3 :(得分:1)

使用子查询来实现此结果:

select field1, calc_field from
( SELECT field1, concat(field2, field3) AS calc_field  FROM MyTable
) as dt
WHERE calc_field LIKE 'A%'

答案 4 :(得分:0)

对于SQL Server,您可以使用+作为串联标识符

SELECT field1, field2 +field3 AS calc_field
  FROM MyTable
  WHERE field2 + field3 LIKE 'A%'

为了获得更好的性能,请避免在WHERE子句中使用连接字段。根据您的要求WHERE(field2 LIKE'A%'或field3 LIKE'A%')可能是更好的选择