在SQL中创建日期范围

时间:2018-05-10 11:04:27

标签: sql oracle

鉴于日期范围:

'20180504' and '20180425'

我想编写一个返回以下日期的查询

'20180504'
'20180503'
'20180502'
'20180501'
'20180430'
'20180429'
'20180428'
'20180427'
'20180426'
'20180425'

有人能建议什么是生成这些日期的最佳方式?日期格式应与上面相同,因为我会用它来从另一个表中提取数据。谢谢!

1 个答案:

答案 0 :(得分:4)

您可以使用分层查询:

SQL Fiddle

查询1

SELECT TO_CHAR( DATE '2018-04-25' + LEVEL - 1, 'YYYYMMDD' ) AS value
FROM   DUAL
CONNECT BY DATE '2018-04-25' + LEVEL - 1 <= DATE '2018-05-04'

<强> Results

|    VALUE |
|----------|
| 20180425 |
| 20180426 |
| 20180427 |
| 20180428 |
| 20180429 |
| 20180430 |
| 20180501 |
| 20180502 |
| 20180503 |
| 20180504 |