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
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.
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.
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.
Returns a unique row number for each row within a window partition. The row number starts at 1 and continues up sequentially.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With