How to do SQL select top N … in AS400

前端 未结 6 757
执笔经年
执笔经年 2020-12-28 13:40

How do you perform a

Select top N * from as400table

type query against an as400/db2 database

6条回答
  •  半阙折子戏
    2020-12-28 14:20

    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.

提交回复
热议问题