开发者

How to do SQL select top N ... in AS400

开发者 https://www.devze.com 2022-12-30 08:07 出处:网络
How do you perform a Select top N * from as400table开发者_运维知识库 type query against an as400/db2 databaseSelect col1,col2

How do you perform a

Select top N * from as400table开发者_运维知识库

type query against an as400/db2 database


Select col1,col2
from 
as400table
where col1='filter'
order by col1
fetch first N row only

Remember to set an ORDER BY clause, because DB2 does not guarantee that the rows returned by FETCH FIRST N ROW ONLY are always the same N.


Strictly, there is no equivalent of TOP N in DB2.

SELECT 1 FROM sysibm.sysdummy1
    WHERE EXISTS (SELECT 2 FROM sysibm.sysdummy1)
FETCH FIRST ROW ONLY

compiles and runs, but

SELECT 1 FROM sysibm.sysdummy1
    WHERE EXISTS (SELECT 2 FROM sysibm.sysdummy1 FETCH FIRST ROW ONLY)

will not compile.

TOP N and FETCH FIRST N are not the same. You can only use FETCH FIRST once per query, whereas TOP N can be used in any sub-select.

You can use a window function in a sub-query in order to simulate TOP N:

select *
from (
    select id, row_number()
    over (order by id) as rn
    from testsch.testtbl
) as r
where r.rn < 100 -- This is N rows you are looking for

This will return exactly 99 rows. I tried that in iSeries 7 and it worked.


Wouldn't it be easier to limit the result instead? Bellow is in order by date and I take the top result

SELECT banana_equipment_id 
FROM new_banana_equipment 
WHERE banana_code=0000001
ORDER BY banana_date DESC 
LIMIT 1;


I am only a baby-geek when it comes to IBM--I am a SQL Server guy. But I found the rownumber approach (which I have used successfully in Oracle) did not work in DB2. I used this one:

SELECT
     MYFIELD 
FROM
     "SCHEMANAME"."TABLENAME" 
WHERE
     FILTERCOL1 = 000001 
     AND FILTERCOL2 = 1 
ORDER BY
     MYFIELD DESC FETCH FIRST ROW ONLY

(I ordered descending because I needed the last value.)

Hope this helps. Joey


It's an old thread, thought I would contribute

Consider using RANK() OVER() for the top n balances?

WITH RANK_TBL AS
        (SELECT FIELD1 AS "ENDING BALANCE",
         RANK() OVER(ORDER BY FIELD1 DESC) AS "RANK NUMBER"
         FROM LIBRARY/TABLE)
SELECT *
FROM RANK_TBL
WHERE "RANK NUMBER" < 6 


I know this is a old thread but probably my answer help to someone, the best way to limit a number of rows in AS400 is using FETCH FIRST 1000 ROWS ONLY Example: select * from myschema.mytable_name FETCH FIRST 1000 ROWS ONLY

This will give you back the first 1000 rows.

Of course the 1000 you can change for whatever other value needed, 10, 25, 10000, etc.

At least this works for me in AS400 database (29-06-2020)

Best

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号