如何使用(AS)TOTAL在哪里,在mssql上?

时间:2013-04-30 15:33:18

标签: sql-server where

如何使用(AS)TOTALNAME在哪里

SELECT 
   *, CITY + ' / ' + NAME AS TOTALNAME
FROM 
   FARKETMEZ
WHERE
   TOTALNAME like '%TURKEY%'

2 个答案:

答案 0 :(得分:2)

您不能使用与ALIAS子句在同一级别上提供的WHERE

您有两种选择:

  • 直接使用表达式

查询:

SELECT  *, CITY + ' / ' + NAME AS TOTALNAME
FROM  FARKETMEZ
WHERE TOTALNAME like '%TURKEY%'
  • 通过包装子查询

查询:

SELECT *
FROM
(    SELECT  *, CITY + ' / ' + NAME AS TOTALNAME
    FROM  FARKETMEZ
) a
WHERE TOTALNAME like '%TURKEY%'

SQL操作顺序如下:

  • FROM clause
  • WHERE子句
  • GROUP BY子句
  • HAVING条款
  • SELECT条款
  • ORDER BY子句

无法直接使用它的原因是因为WHERE子句首先在创建SELECT的{​​{1}}语句之前执行。

答案 1 :(得分:2)

您不能直接使用派生表,也不能使用CTE(SQL Server 2005 +):

派生表:

SELECT *
FROM (  SELECT 
           *, CITY + ' / ' + NAME AS TOTALNAME
        FROM 
           FARKETMEZ
      ) AS T
WHERE TOTALNAME like '%TURKEY%'

CTE:

;WITH CTE AS
(
    SELECT 
           *, CITY + ' / ' + NAME AS TOTALNAME
    FROM 
       FARKETMEZ
)
SELECT *
FROM CTE 
WHERE TOTALNAME like '%TURKEY%'