ORACLE SQL:获取两个数字之间的所有整数

20 sql oracle numbers

有没有办法在Oracle中用SQL选择两个数字之间包含的数字(整数); 我不想创建PL/SQL过程或函数.

例如,我需要得到3到10之间的数字.结果将是值3,4,5,6,7,8,9,10.

谢谢.

Ton*_*ews 51

Oracle的DUAL表的这个技巧也有效:

SQL> select n from
  2  ( select rownum n from dual connect by level <= 10)
  3  where n >= 3;

         N
----------
         3
         4
         5
         6
         7
         8
         9
        10
Run Code Online (Sandbox Code Playgroud)

  • 这种方法的最佳之处在于 Oracle 10g 及更高版本,这不需要块读取 :) (2认同)

pax*_*blo 5

我在创建新数据库时所做的第一件事就是创建并填充一些基本表.

一个是-N和N之间所有整数的列表,另一个是过去5年到未来10年的日期列表(预定作业可以根据需要继续创建这些日期),最后一个是列表全天所有时间.例如,inetgers:

create table numbers (n integer primary key);
insert into numbers values (0);
insert into numbers select n+1 from numbers; commit;
insert into numbers select n+2 from numbers; commit;
insert into numbers select n+4 from numbers; commit;
insert into numbers select n+8 from numbers; commit;
insert into numbers select n+16 from numbers; commit;
insert into numbers select n+32 from numbers; commit;
insert into numbers select n+64 from numbers; commit;
insert into numbers select n+128 from numbers; commit;
insert into numbers select n+256 from numbers; commit;
insert into numbers select n+512 from numbers; commit;
insert into numbers select n+1024 from numbers; commit;
insert into numbers select n+2048 from numbers; commit;
insert into numbers select n+4096 from numbers; commit;
insert into numbers select n+8192 from numbers; commit;
insert into numbers select -n from numbers where n > 0; commit;
Run Code Online (Sandbox Code Playgroud)

这适用于具有自动事务启动的DB2/z,这就是为什么它似乎有裸提交.

是的,它占用了一个(最小)空间,但它只是通过从这些表中选择值来使查询容易编写.它几乎可以在任何基于SQL的DBMS上轻松移植.

您的特定查询将是一个简单的:

select n from numbers where n >=3 and n <= 10;
Run Code Online (Sandbox Code Playgroud)

小时数字和日期范围对我们处理的报告应用程序非常有用.它允许我们为一天中(或多个日期)那些没有任何实际数据的小时创建零条目,而不是(在那个月的第二天没有数据的情况下):

Date       | Quantity
-----------+---------
2009-01-01 |        7
2009-01-03 |       27
2009-01-04 |        6
Run Code Online (Sandbox Code Playgroud)

我们可以得到:

Date       | Quantity
-----------+---------
2009-01-01 |        7
2009-01-02 |        0
2009-01-03 |       27
2009-01-04 |        6
Run Code Online (Sandbox Code Playgroud)