DB2中的ROW_NUMBER()

时间:2014-11-28 07:35:42

标签: sql db2

如何在DB2数据库的where子句中使用ROW_NUMBER()。  我在下面试过,但它不起作用:

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

它给出了错误:无效使用聚合函数或OLAP函数。

我也尝试了以下方式:

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

5 个答案:

答案 0 :(得分:6)

您无法在定义它的同一级别上引用别名。您需要将其包装到派生表中:

SELECT location
FROM (
   SELECT row_number() over(order by location) as rn, 
          location 
   FROM cspapp.locations
)   
WHERE rn < 200

答案 1 :(得分:6)

在基于iSeries DB2中的行号选择时,我使用类似的东西:

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

如果您只对1字段感兴趣,您可以为选择分配名称并引用字段:

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

答案 2 :(得分:3)

你可以尝试FETCH FIRST 200 ROWS而不是row_number。按照正常情况编写你的选择,不需要ROW_NUMBER,按你需要的顺序排序和FETCH FIRST x。

用&#34; *&#34;选择所有列如果您有600多列(并且这本身就是数据库的糟糕设计),那么尤其不是一个好习惯。

答案 3 :(得分:2)

不使用row_number()函数:

SELECT * FROM 
(SELECT * FROM CSPAPP.LOCATIONS ORDER BY LOCATION FETCH FIRST 200 rows only)
ORDER BY LOCATION DESC FETCH FIRST 100 rows only;

With Row number:

SELECT ROW_NUMBER() OVER(ORDER BY LOCATIONS), LOCATIONS as RNM FROM 
(SELECT * FROM CSPAPP.LOCATIONS ORDER BY LOCATIONS FETCH FIRST 200 rows only)
ORDER BY LOCATIONS DESC FETCH FIRST 100 rows only;

答案 4 :(得分:-1)

您可以在定义它的同一级别上引用别名。您需要将其包装到派生表中:

SELECT T1.* FROM(
       SELECT row_number() over(order by location) as rn ,L.* 
       FROM cspapp.locations L) As T1 
WHERE T1.rn < 200

但你应该明白*绝不是最佳做法。您应该使用列名而不是*L.col1)。