select 语句列出范围内的数字

select statement to list numbers in range

在 DB2 中,我有这个查询来列出数字 1-x:

select level from SYSIBM.SYSDUMMY1 connect by level <= "some number"

但是由于 SQL20450N Recursion limit exceeded within a hierarchical query.

当 x 在运行时未知时,如何使用 select 语句生成 1 和 x 之间的数字列表?

当我想要一个与月份相对应的值列表时,我做了类似的事情:

with t1 (mon) as (                                        
  values (1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11),(12)
)
select * from t1                                                        

看起来有点笨拙,但对于像 1-12,甚至 1-50 这样的小列表,它满足了我的需要。

很高兴看到其他人用 DB2 标记他们的问题。

我根据 this post 找到了答案:

WITH d AS
 (SELECT LEVEL - 1 AS dig FROM SYSIBM.SYSDUMMY1 CONNECT BY LEVEL <= 10)
SELECT t1.n
  FROM (SELECT (d7.dig * 1000000) + 
               (d6.dig * 100000) + 
               (d5.dig * 10000) + 
               (d4.dig * 1000) + 
               (d3.dig * 100) + 
               (d2.dig * 10) + 
               d1.dig AS n
          FROM d d1
    CROSS JOIN d d2
    CROSS JOIN d d3
    CROSS JOIN d d4
    CROSS JOIN d d5
    CROSS JOIN d d6
    CROSS JOIN d d7) t1
  JOIN ("subselect that returns desired value as i") t2
    ON t1.n <= t2.i
 ORDER BY t1.n

如果您有任何 table 已知超过 x 行,您总是可以这样做:

select * from (
   select row_number() over () num
      from my_big_table 
) where num <= x

或者,根据 bhamby 的建议:

select row_number() over () num
   from my_big_table 
   fetch first X rows only

对于 DB2,您可以使用递归通用 table 表达式(参见 IBM documentation on recursive CTE):

with max(num) as (
  select 1 from sysibm.sysdummy1
)
,result (num) as (
  select num from max
  union ALL
  select result.num+1
  from result
  where result.num<=100
)
select * from result;

这就是我通常创建列表的方式:

以你为例

numberlist (num) as
(
    select min(1) from anytable 
    union all
    select num + 1 from numberlist
    where num <= x
)