DB2 rownum等价物

时间:2017-03-30 12:23:41

标签: sql db2 db2-luw

我在Oracle中有以下查询,我想在DB2中复制使用随机函数和rownum。

Oracle Query:

SELECT * 
FROM  (
   SELECT * 
   FROM db2admin.QUESTION_BANK 
   WHERE type='PROCESS' 
   ORDER BY dbms_random.value
) WHERE rownum <=?

我得到了随机功能的替代品,但没有用于rownum。以下是DB2中的查询,

SELECT * 
FROM  (
  SELECT * 
  FROM db2admin.QUESTION_BANK 
  WHERE type='PROCESS' ORDER BY RAND
) WHERE rownum <= ?

rownum的值通过PreparedStatement传递。

4 个答案:

答案 0 :(得分:3)

当您在Oracle兼容模式下工作时,DB2有ROWNUM。要启用此功能,请使用:

db2set DB2_COMPATIBILITY_VECTOR=01
db2stop
db2start

要获取所有Oracle功能,请按以下方式启用它:

db2set DB2_COMPATIBILITY_VECTOR=ORA
db2stop
db2start

DB2_COMPATIBILITY_VECTOR上的文档详细介绍了替代方案 ROW_NUMBER() OVER()

答案 1 :(得分:1)

使用ROW_NUMBER()分析函数等效于rownum

SELECT * 
FROM  (
   SELECT db2admin.* 
   , ROW_NUMBER() OVER () rownum 
   FROM db2admin.QUESTION_BANK 
   WHERE type='PROCESS' 
   ORDER BY dbms_random.value
) WHERE rownum <=?

或更妙的是,您可以使用LIMIT子句

SELECT db2admin.* 
, ROW_NUMBER() OVER () rownum 
FROM db2admin.QUESTION_BANK 
WHERE type='PROCESS' 
ORDER BY dbms_random.value
LIMIT :number_of_skiped_rows , :number_of_displayed_rows;

答案 2 :(得分:0)

试一试:

SELECT * 
FROM  (
       SELECT f1.*, rownumber() over(ORDER BY f1.randm ) as rownum
       from ( 
            select f0.*, rand() as randm FROM db2admin.QUESTION_BANK f0
             WHERE f0.type='PROCESS'
            ) f1
      ) f2 
WHERE f2.rownum <= ?

答案 3 :(得分:0)

您可以使用:

SELECT * 
FROM db2admin.QUESTION_BANK 
WHERE type = 'PROCESS' 
ORDER BY RAND() 
fetch first ? rows only;