Reputation: 1731
This is my query:
select * from
(select name,empID,salary,[deducted salary] = salary-7000 from tblEmpDetails
order by Joined_Date) TmpTbl where [decucted salary] > 50000
It was giving error:
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.
Then I changed my query to:
select * from
(select TOP 100 PERCENT name,empID,salary,[deducted salary] = salary-7000
from tblEmpDetails order by Joined_Date) TmpTbl where [decucted salary] > 50000
Now its is working fine.
My query is using TOP 100 is the correct method or any other work around is there for this?
Upvotes: 1
Views: 4873
Reputation: 107706
You would have wanted the ORDER BY in the outer query, e.g.
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
EDIT - Yes you need to include Joined_Date in the inner query to sort by it on the outer query, as well as explicitly listing only the 4 columns desired instead of *
.
But you could also have written the query in one level
select name,empID,salary,[deducted salary] = salary-7000
from tblEmpDetails
where salary-7000 > 50000
order by Joined_Date
Note that salary-7000
although repeated in the query is only evaluated once by SQL Server because it is smart enough to use it twice.
Upvotes: 5