select语句列出范围内的数字

时间:2015-09-29 17:04:01

标签: sql db2

在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之间的数字列表?

5 个答案:

答案 0 :(得分:1)

我找到了基于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

答案 1 :(得分:0)

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

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标记他们的问题。

答案 2 :(得分:0)

如果您知道任何表格的行数超过x行,您可以随时执行:

quietly bysort date id:  gen dup2 = cond(_N==1,0,_N)
list, sepby(date id)

或者,根据bhamby的建议:

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

答案 3 :(得分:0)

对于DB2,您可以使用递归公用表表达式(参见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;

答案 4 :(得分:0)

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

以您为例

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