Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ROW_NUMBER() in DB2

Tags:

sql

db2

How to use ROW_NUMBER() in where clause in DB2 database. I have tried below but it did not work:

SELECT * FROM CSPAPP.LOCATIONS
WHERE (ROW_NUMBER() OVER(ORDER BY LOCATION)) BETWEEN 100 AND 200

It gave error : Invalid use of aggregate function or OLAP function.

I also tried with followiong ways :

SELECT (ROW_NUMBER() OVER(ORDER BY LOCATION)) AS RN ,* FROM CSPAPP.LOCATIONS
WHERE RN < 200

SELECT (ROW_NUMBER() OVER(ORDER BY LOCATION)) AS RN ,LOCATION FROM CSPAPP.LOCATIONS
WHERE RN < 200
like image 786
Mandar Avatar asked Nov 28 '14 07:11

Mandar


People also ask

What is Rownum in db2?

ROWNUM numbers the records in a result set. The first record that meets the WHERE clause criteria in a SELECT statement is given a row number of 1, and every subsequent record meeting that same criteria increases the row number.

What is ROW_NUMBER () function in SQL?

ROW_NUMBER function is a SQL ranking function that assigns a sequential rank number to each new record in a partition. When the SQL Server ROW NUMBER function detects two identical values in the same partition, it assigns different rank numbers to both.

How do I find the number of rows in a db2 table?

The COUNT function returns the number of rows or values in a set of rows or values. The schema is SYSIBM. The argument values can be of any built-in data type other than a BLOB, CLOB, DBCLOB, or XML.

What does ROW_NUMBER () over do?

Returns a unique row number for each row within a window partition. The row number starts at 1 and continues up sequentially.


2 Answers

You can't reference an alias on the same level where it is defined. You need to wrap this into a derived table:

SELECT location
FROM (
   SELECT row_number() over(order by location) as rn, 
          location 
   FROM cspapp.locations
)   
WHERE rn < 200
like image 79
a_horse_with_no_name Avatar answered Oct 14 '22 12:10

a_horse_with_no_name


I use something like this when selecting based on row number in iSeries DB2:

SELECT *
FROM (
    SELECT ROW_NUMBER() OVER(ORDER BY location) as RRN, *
    FROM CSPAPP.LOCATIONS
    )
WHERE RRN between 100 and 200

If you are only interested in the 1 field you may be able to assign a name to the select and reference the fields:

SELECT DATA.location
FROM (
    SELECT ROW_NUMBER() OVER(ORDER BY location) as RRN, *
    FROM CSPAPP.LOCATIONS
    ) as DATA
WHERE DATA.RRN between 100 and 200
like image 43
clutton Avatar answered Oct 14 '22 11:10

clutton