我怎样才能获得oracle过去10年的清单?
这是我的尝试
SELECT TO_CHAR(SYSDATE,'yyyy') FROM DUAL
UNION ALL
SELECT TO_CHAR(ADD_MONTHS(SYSDATE,-12),'yyyy') FROM DUAL
UNION ALL
SELECT to_char(add_months(sysdate,-24),'yyyy') FROM DUAL
UNION ALL
SELECT TO_CHAR(ADD_MONTHS(SYSDATE,-36),'yyyy') FROM DUAL
UNION ALL
SELECT TO_CHAR(ADD_MONTHS(SYSDATE,-48),'yyyy') FROM DUAL
UNION ALL
SELECT TO_CHAR(ADD_MONTHS(SYSDATE,-60),'yyyy') FROM DUAL
UNION ALL
SELECT TO_CHAR(ADD_MONTHS(SYSDATE,-72),'yyyy') FROM DUAL
UNION ALL
SELECT TO_CHAR(ADD_MONTHS(SYSDATE,-84),'yyyy') FROM DUAL
答案 0 :(得分:12)
让我先从一个简单的技巧开始
SELECT LEVEL FROM
DUAL
CONNECT BY LEVEL <= 10;
这将生成1,2 .... 10的行。
它有效,因为CONNECT BY
会尝试链接行。每个都有一个水平。现在我们提到LEVEL <= 10
,因此生成了10行。!!!
您现在的问题是,从SYSDATE
10次减去12个月。
所以,答案是
SELECT TO_CHAR(SYSDATE,'YYYY')-LEVEL+1 FROM
DUAL
CONNECT BY LEVEL <= 10;
现在,您可以启动您的创造力,根据需要自定义此SQL。
最好的运气!
答案 1 :(得分:1)
简单的递归查询和一些基本的数学运算将实现这一目标:
SELECT CAST (TO_CHAR (SYSDATE, 'yyyy') AS NUMBER) - LEVEL + 1 AS year
FROM DUAL
CONNECT BY LEVEL <= 10
答案 2 :(得分:1)
您可以按级别连接&#34;技巧&#34;生成行:
select to_char(add_months(trunc(sysdate, 'yyyy'), -12*(level -1)), 'yyyy') yr
from dual
connect by level <= 10; -- possibly 11 if you want this year along with the previous 10 years
YR
----
2015
2014
2013
2012
2011
2010
2009
2008
2007
2006