How to use the WHERE clause over a column made from row_number () over ()

2

I am trying to use the where on top of a column generated by row_number but it does not work; is it possible to do this?

    
asked by anonymous 23.09.2018 / 00:48

2 answers

4

Yes, one way is through the use of CTE.

-- código #1
with Sequenciado as (
SELECT *,
       seq= row_number() over (partition by colA order by colB)
  from tabA
)
SELECT seq, colA, colB
  from Sequenciado
  where seq between 1 and 5;

The above code uses CTE (common table expression), which makes it easier to understand and maintain it. See article " Modular Programming with Table Expressions (CTE) / a> ".

    
23.09.2018 / 01:01
2

You can also use a subquery:

SELECT seq, 
       colA, 
       colB
FROM
    (
        SELECT *,
               ROW_NUMBER() OVER (PARTITION BY colA ORDER BY colB) AS Seq
        FROM tabA
    ) AS T
WHERE T.Seq BETWEEN 1 AND 5;
    
23.09.2018 / 20:05