Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: Use a calculated fields from the SELECT in the WHERE clause

I have a SQL query that does some ranking, like this:

SELECT RANK() OVER(PARTITION BY XXX ORDER BY yyy,zzz,oooo) as ranking, * 
FROM SomeTable
WHERE ranking = 1 --> this is not possible

I want to use that ranking in a WHERE condition at the end.

Now I nest this query in another query and do filtering on the ranking there, but is there no easier or faster way to filter on such values from the SELECT statement?

like image 657
Erik Dekker Avatar asked Dec 28 '22 07:12

Erik Dekker


2 Answers

Use a CTE (Common Table Expression) - sort of an "inline" view just for the next statement:

;WITH MyCTE AS
(
    SELECT 
        RANK() OVER(PARTITION BY XXX ORDER BY yyy,zzz,oooo) as ranking, 
        * 
    FROM SomeTable
) 
SELECT * 
FROM MyCTE
WHERE ranking = 1 --> this is now possible!
like image 159
marc_s Avatar answered Mar 22 '23 23:03

marc_s


Sorry for the former posting, i forgot : windowing functions can only be used in select or order by clauses. You'll have to use a sub query:

SELECT * FROM 
(
  SELECT RANK() OVER(PARTITION BY XXX ORDER BY yyy,zzz,oooo) as ranking, * 
  FROM SomeTable
) t
WHERE ranking = 1

OR A CTE.

like image 45
Mithrandir Avatar answered Mar 23 '23 00:03

Mithrandir