我需要从现在开始过去10天 我目前有以下Oracle sql查询来获取最近10个日期。
WITH DATES AS (
SELECT sysdate - 10 AS value_date FROM dual
UNION
SELECT sysdate - 9 AS value_date FROM dual
UNION
SELECT sysdate - 8 AS value_date FROM dual
UNION
SELECT sysdate - 7 AS value_date FROM dual
UNION
SELECT sysdate - 6 AS value_date FROM dual
UNION
SELECT sysdate - 5 AS value_date FROM dual
UNION
SELECT sysdate - 4 AS value_date FROM dual
UNION
SELECT sysdate - 3 AS value_date FROM dual
UNION
SELECT sysdate - 2 AS value_date FROM dual
UNION
SELECT sysdate - 1 AS value_date FROM dual
UNION
SELECT sysdate AS value_date FROM dual
UNION
SELECT sysdate + 1 AS value_date FROM dual
但我想要一个更合适有效的方法来获得过去的10个日期。 Union查询看起来很脏。 我如何在Oracle SQL中执行此操作?
答案 0 :(得分:3)
使用与CONNECT BY子句更紧凑的等效项:
SELECT trunc( sysdate ) - level + 2
FROM dual
CONNECT BY rownum <= 12
演示:http://sqlfiddle.com/#!4/a50e25/5
| TRUNC(SYSDATE)-LEVEL+2 |
|------------------------|
| 2017-09-15T00:00:00Z |
| 2017-09-14T00:00:00Z |
| 2017-09-13T00:00:00Z |
| 2017-09-12T00:00:00Z |
| 2017-09-11T00:00:00Z |
| 2017-09-10T00:00:00Z |
| 2017-09-09T00:00:00Z |
| 2017-09-08T00:00:00Z |
| 2017-09-07T00:00:00Z |
| 2017-09-06T00:00:00Z |
| 2017-09-05T00:00:00Z |
| 2017-09-04T00:00:00Z |
答案 1 :(得分:1)
您可以使用分层查询获得与查询相同的结果(也使用TRUNC()
将日期截断为当天开始的午夜):
SELECT TRUNC( SYSDATE ) - 11 + LEVEL
FROM DUAL
CONNECT BY LEVEL <= 12
或者,使用递归子查询分解子句:
WITH days ( dt ) AS (
SELECT TRUNC( SYSDATE ) - 10 FROM DUAL
UNION ALL
SELECT dt + 1 FROM days WHERE dt <= SYSDATE
)
SELECT dt FROM days