我有一个SQL查询,它接受一个日期参数(如果我把它扔进一个函数),我需要在去年的每一天运行它.
如何生成过去365天的列表,所以我可以使用直接SQL来做到这一点?
显然生成列表0..364也可以,因为我总能:
SELECT SYSDATE - val FROM (...);
user34850.. 87
无需使用超大表或ALL_OBJECTS表:
SELECT TRUNC (SYSDATE - ROWNUM) dt FROM DUAL CONNECT BY ROWNUM < 366
会做的.
无需使用超大表或ALL_OBJECTS表:
SELECT TRUNC (SYSDATE - ROWNUM) dt FROM DUAL CONNECT BY ROWNUM < 366
会做的.
SELECT (sysdate-365 + (LEVEL -1)) AS DATES FROM DUAL connect by level <=( sysdate-(sysdate-365))
如果替换'from'和'to'日期代替sysdate和sysdate-365,则输出将是from和date之间的日期范围.
最近我遇到了类似的问题并通过这个简单的查询解决了它:
SELECT (to_date(:p_to_date,'DD-MM-YYYY') - level + 1) AS day FROM dual CONNECT BY LEVEL <= (to_date(:p_to_date,'DD-MM-YYYY') - to_date(:p_from_date,'DD-MM-YYYY') + 1);
例
SELECT (to_date('01-05-2015','DD-MM-YYYY') - level + 1) AS day FROM dual CONNECT BY LEVEL <= (to_date('01-05-2015','DD-MM-YYYY') - to_date('01-04-2015','DD-MM-YYYY') + 1);
结果
01-05-2015 00:00:00 30-04-2015 00:00:00 29-04-2015 00:00:00 28-04-2015 00:00:00 27-04-2015 00:00:00 26-04-2015 00:00:00 25-04-2015 00:00:00 24-04-2015 00:00:00 23-04-2015 00:00:00 22-04-2015 00:00:00 21-04-2015 00:00:00 20-04-2015 00:00:00 19-04-2015 00:00:00 18-04-2015 00:00:00 17-04-2015 00:00:00 16-04-2015 00:00:00 15-04-2015 00:00:00 14-04-2015 00:00:00 13-04-2015 00:00:00 12-04-2015 00:00:00 11-04-2015 00:00:00 10-04-2015 00:00:00 09-04-2015 00:00:00 08-04-2015 00:00:00 07-04-2015 00:00:00 06-04-2015 00:00:00 05-04-2015 00:00:00 04-04-2015 00:00:00 03-04-2015 00:00:00 02-04-2015 00:00:00 01-04-2015 00:00:00