DB2 Over子句的问题

时间:2010-03-29 20:29:29

标签: sql db2

我正在尝试使用非常旧版本的DB2进行分页,而我唯一可以选择行范围的方法就是使用OVER命令。

此查询提供了正确的结果(我要分页的结果)。

select MIN(REFID) as REFID, REFGROUPID from ARMS_REFERRAL where REFERRAL_ID<>'Draft' and REFERRAL_ID not like 'Demo%' group by REFGROUPID order by REFID desc

结果:

   REFID       REFGROUPID
    302         242
    301         241
    281         221
    261         201
    225         142
    221         161
    ...         ...

SELECT * FROM ( SELECT row_number() OVER () AS rid, MIN(REFID) AS REFID, REFGROUPID FROM arms_referral where REFERRAL_ID<>'Draft' and REFERRAL_ID not like 'Demo%'  group by REFGROUPID order by REFID desc ) AS t WHERE t.rid BETWEEN 1 and 5

结果:

REFID       REFGROUPID
26          12
22          11
14          8
11          7
6           4

正如您所看到的,它确实选择了前五行,但显然没有选择最新的行。

如果我将一个Order By子句添加到OVER(),它会更接近,但仍然不完全正确。

SELECT * FROM ( SELECT row_number() OVER (ORDER BY REFGROUPID desc) AS rid, MIN(REFID) AS REFID, REFGROUPID FROM arms_referral where REFERRAL_ID<>'Draft' and REFERRAL_ID not like 'Demo%'  group by REFGROUPID order by REFID desc ) AS t WHERE t.rid BETWEEN 1 and 5

REFID       REFGROUPID
302         242
301         241
281         221
261         201
221         161

它非常接近,但第5个结果不正确(实际上是第6个结果)。

如何使此查询正确,以便它可以按REFGROUPID分组然后按REFID排序?

1 个答案:

答案 0 :(得分:1)

如果你把订单放在parens的外面怎么办?

SELECT * 
FROM ( SELECT row_number() OVER (ORDER BY REFGROUPID desc) AS rid, 
MIN(REFID) AS REFID, REFGROUPID FROM arms_referral where REFERRAL_ID<>'Draft' 
and REFERRAL_ID not like 'Demo%'  group by REFGROUPID ) AS t 
WHERE t.rid BETWEEN 1 and 5 order by REFID desc