SQL查询服务器在SELECT查询中按TOP 100 PERCENT排序

时间:2013-05-08 04:27:27

标签: sql sql-server-2008 tsql

这是我的疑问:

select * from   
(select name,empID,salary,[deducted salary] = salary-7000 from tblEmpDetails   
order by Joined_Date) TmpTbl where [decucted salary] > 50000

这是错误的:

The ORDER BY clause is invalid in views, inline functions, derived tables,   
subqueries, and common table expressions, unless TOP or FOR XML is also specified.

然后我将查询更改为:

select * from   
(select TOP 100 PERCENT name,empID,salary,[deducted salary] = salary-7000   
from tblEmpDetails order by Joined_Date) TmpTbl where [decucted salary] > 50000 

现在工作正常 我的查询是使用TOP 100是正确的方法还是有任何其他的解决方法?

1 个答案:

答案 0 :(得分:5)

您可能希望在外部查询中使用ORDER BY,例如

select name,empID,salary,[deducted salary] from   
(select name,empID,salary,[deducted salary] = salary-7000, Joined_Date
   from tblEmpDetails   
) TmpTbl where [decucted salary] > 50000
order by Joined_Date

编辑 - 是的,您需要在内部查询中包含Joined_Date,以便在外部查询中对其进行排序,以及仅显示所需的4列而不是*。< / p>

但您也可以在一个级别编写查询

  select name,empID,salary,[deducted salary] = salary-7000
    from tblEmpDetails
   where salary-7000 > 50000
order by Joined_Date

请注意,salary-7000虽然在查询中重复,但SQL Server只能评估一次,因为它足够聪明,可以使用它两次。