Problem with DB2 Over clause

Posted by silent1mezzo on Stack Overflow See other posts from Stack Overflow or by silent1mezzo
Published on 2010-03-29T20:29:28Z Indexed on 2010/03/29 20:33 UTC
Read the original article Hit count: 179

Filed under:
|

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.

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.

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).

How do I make this query correct so it can group by a REFGROUPID and then order by the REFID?

© Stack Overflow or respective owner

Related posts about db2

Related posts about sql