简体   繁体   English

DB2 Over子句出现问题

[英]Problem with DB2 Over clause

I'm trying to do pagination with a very old version of DB2 and the only way I could figure out selecting a range of rows was to use the OVER command. 我正在尝试对一个非常旧的DB2版本进行分页,而我可以确定选择一系列行的唯一方法是使用OVER命令。

This query provide's the correct results (the results that I want to paginate 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

Results: 结果:

   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

Results: 结果:

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

As you can see, it does select the first five rows, but it's obviously not selecting the latest. 如您所见,它确实选择了前五行,但是显然没有选择最新的行。

If I add a Order By clause to the OVER() it gets closer, but still not totally correct. 如果我在OVER()上添加Order By子句,它会更接近,但仍不完全正确。

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

It's really close but the 5th result isn't correct (actually the 6th result). 确实很接近,但是第5个结果不正确(实际上是第6个结果)。

How do I make this query correct so it can group by a REFGROUPID and then order by the REFID? 如何使此查询正确无误,以便可以按REFGROUPID分组,然后按REFID排序?

what if you put the order by on the outside of the 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM