2

我的查询是这样的。

select id,name,salary,(salary-2000) AS [Deductedsalary]  
from EmployeeDetails

我想在 where 子句中使用 [Deductedsalary] 列,类似于下面的查询。

select 
    id, name, salary, (salary-2000) AS [Deductedsalary]  
from 
    EmployeeDetails 
where 
    [Deductedsalary] > 5000

注意:我不想使用带有“salary”列的过滤查询

4

4 回答 4

2

您不能直接执行此操作 - 您必须在基础Salary列上进行过滤,或者使用 CTE 之类的东西:

WITH CTE AS 
(
   SELECT
       id, name, salary, 
       DeductedSalary = salary - 2000
   FROM
       dbo.EmployeeDetails 
)
SELECT 
   id, name, salary, DeductedSalary
FROM 
   CTE
WHERE
   [Deductedsalary] > 5000
于 2013-05-04T11:08:14.810 回答
2

您可以使用子查询来定义别名:

select  *
from    (
        select  salary-2000 as deducted_salary
        ,       *
        from 
                EmployeeDetails 
        ) SubQueryAlias
where   Deductedsalary > 5000
于 2013-05-04T11:10:19.460 回答
2

另一种方法是

SELECT id,
       name,
       salary,
       DeductedSalary
FROM   EmployeeDetails
CROSS APPLY (SELECT salary-2000) DS(DeductedSalary)
WHERE  DeductedSalary > 5000 

虽然我会用

SELECT id,
       name,
       salary,
       ( salary - 2000 ) AS [Deductedsalary]
FROM   EmployeeDetails
WHERE  [salary] > 7000 

因为这是可预测的(可以使用索引并且会有更好的基数估计)

于 2013-05-04T11:14:45.867 回答
1

你可以试试

Select *
    FROM
    (
        select 
          id, name, salary, (salary-2000) AS [Deductedsalary]  
        from 
           EmployeeDetails 

    ) data
    where 
          [Deductedsalary] > 5000
于 2013-05-04T11:10:00.133 回答