Oracle-10g

在 oracle sql 查詢中創建增量數字

  • July 28, 2017

如何在不創建任何表的情況下在 oracle sql 查詢中創建增量數字?我曾嘗試使用“with”子句,但未能得到預期的結果。我正在使用 oracle 10g

這是我嘗試的程式碼,它似乎不起作用:

WITH
TABLE3 AS ( SELECT 2008 YEARS FROM dual WHERE 1=1
union all
select t3.YEARS+1 from TABLE3 t3
WHERE 1=1 AND t3.YEARS < 2011
)

select YEARS from TABLE3

我想要的預期結果是:

2008
2009
2010
2011

類似於 Kerri 的答案,但沒有with(並受到SO 答案的啟發):

SELECT 2007 + LEVEL AS YEARS
FROM DUAL
CONNECT BY LEVEL <= 4;

    YEARS
----------
     2008
     2009
     2010
     2011

或者,如果您的目標是獲取目前年份的前三年,而不對開始年份進行硬編碼:

SELECT EXTRACT(YEAR FROM SYSDATE) + 1 - LEVEL AS YEARS
FROM DUAL
CONNECT BY LEVEL <= 4
ORDER BY YEARS;

認為這將起作用(基於此頁面(http://psoug.org/definition/LEVEL.htm)作為起點):

WITH counter
AS ( SELECT LEVEL seq
      FROM DUAL
    CONNECT BY LEVEL <= 4 )
SELECT (2008 + seq - 1) myYear
 FROM counter
ORDER BY 1
;

這應該返回:

myYear
------
 2008
 2009
 2010
 2011

調整 2008 和 4 以獲得不同的結果。

引用自:https://dba.stackexchange.com/questions/3140