简体   繁体   中英

Rank Function inside case statement

I am trying to use Rank Function inside a case statement and give where rank_number = 1 , it's throwing error as unexpected where Condition. Can some one help me how to assign rank in where clause inside case statement

You can't use the RANK() analytic function (or any other one, for that matter) in the WHERE clause of a query. The results of the rank computation are not yet available. But they are available in the SELECT clause or the ORDER BY clause. One workaround would be to subquery:

SELECT *
FROM
(
    SELECT t.*, RANK() OVER (ORDER BY blah) rnk
    FROM yourTable t
) s
WHERE rnk = 1;

Some databases support a QUALIFY clause, where it is possible to use analytic functions. Assuming you are using something like Teradata or BigQuery, you could use:

SELECT *
FROM yourTable
WHERE 1 = 1
QUALIFY RANK() OVER (ORDER BY blah) = 1;

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