Answers:
与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得到不同的结果。
看来OP试图使用递归子查询解决问题。这在10g中不起作用,因为该功能直到11.2才被添加,但是在11.2+中,以下内容也是解决该问题的有效方法。
WITH T3(Years) AS (
SELECT 2008 Years FROM dual
UNION ALL
SELECT Years + 1 FROM T3 WHERE Years < 2011
)
SELECT * FROM T3;
OP的查询中唯一缺少的是(YEARS)
。
WITH T3(Years) AS ( SELECT 2008 Years UNION ALL SELECT Years + 1 FROM T3 WHERE Years < 2011 ) SELECT * FROM T3;
FROM dual
。
dual
是特定于oracle的表。其他数据库(例如MS SQL Sever,mysql,postgres)允许使用语句select expression
。mysql确实也知道一个双重表
为什么不只是创建一个序列?
CREATE SEQUENCE TEMP_YEAR_sEQUENCE START WITH 2008;
SELECT TEMP_YEAR_sEQUENCE.NEXTVAL FROM DUAL;
....
DROP SEQUENCE TEMP_YEAR_SEQUENCE;
编辑:
对于较小范围的序列值,您可以使用如下所示的内容:
select ROWNUM + 10 # start value
from ALL_OBJECTS
where ROWNUM <= 5 ; # count of values
您只需要一个具有足够行数的表。
这是一个基于case语句添加多个标志并对其进行递增的示例。
WITH T3(FLAG1,FLAG2,FLAG3,tt,OTHER_DATA)
AS (
SELECT '0' FLAG1, '0' FLAG2, '0' FLAG3 , current_timestamp tt , 'dummy' OTHER_DATA
FROM dual
UNION ALL
SELECT case when cast( FLAG2 as int) > 5 then
cast ((cast(FLAG1 as int) + 1) as varchar2(30)) else FLAG1 end FLAG1,
cast((cast(FLAG2 as int) + 1) as varchar2(30)) FLAG2 ,case when (
(FLAG2 ='3') or (FLAG2 = '4')) then cast ((cast( FLAG3 as int) + 1)
as varchar2(30)) else FLAG3 end FLAG3 ,current_timestamp tt ,
'ACTUAL' OTHER_DATA FROM T3 WHERE FLAG2 < 10
)
SELECT * FROM T3
WHERE OTHER_DATA != 'dummy' ;
-结果集如下
Flag1 Flag2 Flag3 TT OTHER_DATA
0 1 0 21-DEC-15 08.31.05.229502000 PM ASIA/CALCUTTA ACTUAL
0 2 0 21-DEC-15 08.31.05.229502000 PM ASIA/CALCUTTA ACTUAL
0 3 0 21-DEC-15 08.31.05.229502000 PM ASIA/CALCUTTA ACTUAL
0 4 1 21-DEC-15 08.31.05.229502000 PM ASIA/CALCUTTA ACTUAL
0 5 2 21-DEC-15 08.31.05.229502000 PM ASIA/CALCUTTA ACTUAL
0 6 2 21-DEC-15 08.31.05.229502000 PM ASIA/CALCUTTA ACTUAL
1 7 2 21-DEC-15 08.31.05.229502000 PM ASIA/CALCUTTA ACTUAL
2 8 2 21-DEC-15 08.31.05.229502000 PM ASIA/CALCUTTA ACTUAL
3 9 2 21-DEC-15 08.31.05.229502000 PM ASIA/CALCUTTA ACTUAL
4 10 2 21-DEC-15 08.31.05.229502000 PM ASIA/CALCUTTA ACTUAL