Sql 范围在两个日期之间选择
我有一个Oracle11g,我想知道是否可以从一个日期选择另一个日期 例如: 我有两个字段,分别是StartDate和EndDate。我想显示EndDate和StartDate之间的行数。 如果我的起始日期为2018-08-01,结束日期为2018-08-10,那么我的预期表格应为:Sql 范围在两个日期之间选择,sql,oracle,oracle11g,range,Sql,Oracle,Oracle11g,Range,我有一个Oracle11g,我想知道是否可以从一个日期选择另一个日期 例如: 我有两个字段,分别是StartDate和EndDate。我想显示EndDate和StartDate之间的行数。 如果我的起始日期为2018-08-01,结束日期为2018-08-10,那么我的预期表格应为: DATE | rownum 2018-08-01 | 1 2018-08-02 | 2 2018-08-03 | 3 2018-08-04 | 4 2018-08-05 | 5 2018-08-06 |
DATE | rownum
2018-08-01 | 1
2018-08-02 | 2
2018-08-03 | 3
2018-08-04 | 4
2018-08-05 | 5
2018-08-06 | 6
2018-08-07 | 7
2018-08-08 | 8
2018-08-09 | 9
2018-08-10 | 10
谢谢大家! 您可能需要如下所示的行生成器:
select date '2018-08-01' + level -1 as yourDate,
level as yourRowNum
from dual
connect by date '2018-08-01' + level -1 <= date '2018-08-10'
要避免重复日期值,可以使用:
with dateRange(startDate, endDate) as
(
select date '2018-08-01', date '2018-08-10'
from dual
)
select startDate + level -1 as yourDate,
level as yourRowNum
from dateRange
connect by startDate + level -1 <= endDate;
通过使用sum1而不是按日期订购,您可以轻松获得您想要的: 其他备选方案count1、row_编号也可替换为sum1
我猜你想要这样的东西
WITH my_table AS
(SELECT TRUNC(SYSDATE) + LEVEL - 1 AS current_day
FROM DUAL
CONNECT BY LEVEL < 10)
SELECT FIRST_VALUE(current_day) OVER (ORDER BY current_day) first_day
, current_day
, current_day - FIRST_VALUE(current_day) OVER (ORDER BY current_day) days_diff
FROM my_TABLE;
FIRST_DAY CURRENT_DAY DAYS_DIFF
--------- ----------- ----------
29-AUG-18 29-AUG-18 0
29-AUG-18 30-AUG-18 1
29-AUG-18 31-AUG-18 2
29-AUG-18 01-SEP-18 3
29-AUG-18 02-SEP-18 4
29-AUG-18 03-SEP-18 5
29-AUG-18 04-SEP-18 6
29-AUG-18 05-SEP-18 7
29-AUG-18 06-SEP-18 8
9 rows selected.
显示行数是什么意思?行数为10;您在预期的表中显示了一些非常不同的内容。如果您的问题描述不清楚,我们将无法帮助您。谢谢Aleksej!它非常有用!我不得不改变一些事情,但这个解决方案对我有效!
select "Date", sum(1) over (order by "Date") "Row Number"
from tab
where "Date" between date'2018-08-01' and date'2018-08-10';
Date Row Number
---------- ----------
2018-08-01 1
2018-08-02 2
2018-08-03 3
2018-08-04 4
2018-08-05 5
2018-08-06 6
2018-08-07 7
2018-08-08 8
2018-08-09 9
2018-08-10 10
WITH my_table AS
(SELECT TRUNC(SYSDATE) + LEVEL - 1 AS current_day
FROM DUAL
CONNECT BY LEVEL < 10)
SELECT FIRST_VALUE(current_day) OVER (ORDER BY current_day) first_day
, current_day
, current_day - FIRST_VALUE(current_day) OVER (ORDER BY current_day) days_diff
FROM my_TABLE;
FIRST_DAY CURRENT_DAY DAYS_DIFF
--------- ----------- ----------
29-AUG-18 29-AUG-18 0
29-AUG-18 30-AUG-18 1
29-AUG-18 31-AUG-18 2
29-AUG-18 01-SEP-18 3
29-AUG-18 02-SEP-18 4
29-AUG-18 03-SEP-18 5
29-AUG-18 04-SEP-18 6
29-AUG-18 05-SEP-18 7
29-AUG-18 06-SEP-18 8
9 rows selected.