简体   繁体   中英

SQL: SyntaxError: order by with row_number() function

I have the following table Employee :

+----+--------+
| Id | Salary |
+----+--------+
| 1  | 150    |
| 2  | 290    |
| 3  | 302    |
+----+--------+

I am using the following code to find the second highest salary:

with t as 
(
    select 
        Salary, 
        row_number() over (order by Salary desc) as salary_ord 
    from 
        Employee
)
select Salary 
from t 
where salary_ord == 2

However, I get an error:

SyntaxError: near 't as (
select Salary, row_number() over (order by Salary desc) as salary_ord'

What did I do wrong here? Thanks!

In SQL, the correct comparison operator is = , not == . So, this is the ANSI SQL version of your query:

with t as (
      select Salary, row_number() over (order by Salary desc) as salary_ord 
      from Employee
     )
select Salary
from t
where salary_ord = 2;

However, your error suggests that your database doesn't support with or window functions.

In SQL Server,

You can do:

select top 1 Salary 
from Employee 
order by Salary desc
offset 1 row fetch next 1 row only

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM