176.第二高的薪水
176. Second Highest Salary
select salary
from employee
order by salary desc limit 2
having salary <> max(salary)
select salary
from employee
order by salary desc limit 1
having salary not in (select max(salary) from employee);
上述查询无效并给出响应
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'having salary <> max(salary)' at line 2
由于 having 用于聚合器功能,因此在我看来这应该可行。
请帮助我解释为什么它不起作用我也在努力学习SQL查询如果可能请为我提供资源。
我们要第二高的薪水。
<!-- -->
> create table employee (salary int);
> insert into employee values (1),(2),(3),(4),(5),(6),(7),(8);
>
> <pre>
> ✓
>
> ✓
> </pre>
<!-- -->
> select salary
> from employee
> order by salary desc
> limit 1, 1 ;
>
> <pre>
> | salary |
> | -----: |
> | 7 |
> </pre>
*db<>fiddle [here](https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=ddf303748ee5620b2334b95621024840)*
另一个选项是使用 window 函数:
WITH cte AS
(
SELECT *,
DENSE_RANK() OVER (ORDER BY salary Desc) AS Rnk
FROM employee
)
SELECT cte.salary
FROM cte
WHERE Rnk=2;
请注意,如果您有薪水 5000, 5000, 3000
,正如@Thorsten Kettner 在评论中提到的那样,第二高的薪水将是 3000。
https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=90c67881bcf6fd8f0c50a5a351f6b9ca
select salary
from employee
order by salary desc limit 2
having salary <> max(salary)
select salary
from employee
order by salary desc limit 1
having salary not in (select max(salary) from employee);
上述查询无效并给出响应
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'having salary <> max(salary)' at line 2
由于 having 用于聚合器功能,因此在我看来这应该可行。
请帮助我解释为什么它不起作用我也在努力学习SQL查询如果可能请为我提供资源。
我们要第二高的薪水。
<!-- -->
> create table employee (salary int);
> insert into employee values (1),(2),(3),(4),(5),(6),(7),(8);
>
> <pre>
> ✓
>
> ✓
> </pre>
<!-- -->
> select salary
> from employee
> order by salary desc
> limit 1, 1 ;
>
> <pre>
> | salary |
> | -----: |
> | 7 |
> </pre>
*db<>fiddle [here](https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=ddf303748ee5620b2334b95621024840)*
另一个选项是使用 window 函数:
WITH cte AS
(
SELECT *,
DENSE_RANK() OVER (ORDER BY salary Desc) AS Rnk
FROM employee
)
SELECT cte.salary
FROM cte
WHERE Rnk=2;
请注意,如果您有薪水 5000, 5000, 3000
,正如@Thorsten Kettner 在评论中提到的那样,第二高的薪水将是 3000。
https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=90c67881bcf6fd8f0c50a5a351f6b9ca