Can somebody tell me how this sql query evaluates :
SELECT e.sal
FROM employees e
WHERE 1 >= (
SELECT count(*)
FROM employess s
WHERE s.sal>e.sal
)
I know this query returns 1st and 2nd highest salary. But I want to understand the working of this query. I want to know how it returns 1st and 2nd highest salary. Please explain in detail.
The subselect
(SELECT count(*) FROM employess s WHERE s.sal>e.sal)
returns number of employees with salary greater than the current employee you looking at in the top level select
.
So the query basically says give me all employees such that have 1 or less other employees earn more than them
Pretty straight forward though horribly inefficient. The easier way would be simply this:
select top 2 * from employees order by sal desc
EDIT: This will return top 2 employees with highest salary, which as Gordon noted is not the same as top 2 distinct salary values, since people may have exactly the same salary. If that is a concern that you'd have to dedupe it first like this:
select top 2 sal from employees group by sal order by sal desc
To get your 1st and 2nd highest salary, I'd use ROW_NUMBER()
. That should make it easy to understand the rankings of the salaries. Or if you need to account for ties, look into using RANK()
.
Something like this should work:
SELECT sal, Row
FROM (
SELECT sal, ROW_NUMBER() OVER(ORDER BY sal DESC) AS Row
FROM employees e ) t
WHERE Row IN (1,2);
And here is the SQL Fiddle .
Good luck.
That query should return everything.
(SELECT count(*) FROM employess s WHERE s.sal>e.sal)
Since e.sal will NEVER be > e.sal (1 can never be > 1), thus, the count(*) will always be 0. and SELECT e.sal FROM employees e WHERE 1 >= (0)
will always be everything
If you want to return the top 2 salary, you might want to try this:
SELECT TOP 2 * FROM employess AS e ORDER BY e.sal DESC
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.