如何根据当前日期返回包含过去四年的行集?
如果此查询在12/31/2010运行,则应返回:
2007
2008
2009
2010
但如果它在2011年1月1日运行,它应该返回:
2008
2009
2010
2011
这是我开始的,两个返回起始年份的查询。我更喜欢第二种,因为转换为字符串对我来说感觉有点脏。
SELECT TO_CHAR(TRUNC(sysdate, 'YY') - INTERVAL '3' YEAR, 'YYYY') FROM DUAL;
SELECT EXTRACT (YEAR FROM sysdate) - 3 FROM DUAL;
但我不知道如何生成行来充实它。在SQL Server中,我使用the fn_nums function on this page中的CTE。
答案 0 :(得分:5)
显示1到100之间的数字:
SELECT LEVEL
FROM DUAL
CONNECT BY LEVEL <= 100
ORDER BY LEVEL
要更改最大值,请在第三行更改。
答案 1 :(得分:3)
这是一种方式:
SELECT yr
FROM ( SELECT EXTRACT (YEAR FROM (ADD_MONTHS ( SYSDATE, - ( (LEVEL - 1) * 12)))) yr
FROM DUAL
CONNECT BY LEVEL <= 4)
ORDER BY yr;
或者:
SELECT yr
FROM ( SELECT EXTRACT (YEAR FROM sysdate) - (level -1 ) yr
FROM DUAL
CONNECT BY LEVEL <= 4)
ORDER BY yr;
或者:
SELECT yr
FROM (SELECT EXTRACT (YEAR FROM SYSDATE) - (x - 1) yr
FROM DUAL
MODEL
DIMENSION BY (1 AS z)
MEASURES (1 x)
RULES
ITERATE (4)
(x [ITERATION_NUMBER] = ITERATION_NUMBER + 1))
ORDER BY yr;
答案 2 :(得分:1)
与接受的答案类似,您可以使用with子句替换内联视图。我发现with子句更具可读性。特别是如果您要作为同一查询的一部分对即时NUMBERS表执行多次计算 - 整个SQL语句更具可读性。
动态数字表:
WITH NUMBERS_START_AT_ZERO AS
(SELECT LEVEL - 1 AS NUM
FROM DUAL
CONNECT BY LEVEL <= 4
order by NUM desc)
SELECT EXTRACT (YEAR FROM sysdate) - NUM AS YEARS
FROM NUMBERS_START_AT_ZERO
<强>输出:强>
YEARS
2009
2010
2011
2012