Home > Database > Mysql Tutorial > How to Use ROW_NUMBER() in a WHERE Clause?

How to Use ROW_NUMBER() in a WHERE Clause?

Barbara Streisand
Release: 2024-12-18 14:19:11
Original
111 people have browsed it

How to Use ROW_NUMBER() in a WHERE Clause?

Querying Using ROW_NUMBER() Function in WHERE Clause

In an attempt to utilize the ROW_NUMBER() function in a WHERE clause, a query encountered the error "Windowed functions can only appear in the SELECT or ORDER BY clauses." The query in question was:

SELECT employee_id
FROM v_employee
WHERE ROW_NUMBER() OVER (ORDER BY employee_id) > 0
ORDER BY employee_id
Copy after login

To resolve this error, employ a workaround by wrapping the select statement within a Common Table Expression (CTE). This allows querying against the CTE and utilizing the windowed function's results in the WHERE clause.

WITH MyCte AS 
(
    select   employee_id,
             RowNum = row_number() OVER ( order by employee_id )
    from     V_EMPLOYEE 
    ORDER BY Employee_ID
)
SELECT  employee_id
FROM    MyCte
WHERE   RowNum > 0
Copy after login

The above is the detailed content of How to Use ROW_NUMBER() in a WHERE Clause?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template