可用日期范围(按年份)
Available date range by year
我有一个 table 保存日期
ID Dates
1 2014-01-20
2 2014-01-21
...
100 2014-05-20
101 2014-06-01 --Missing a few dates
102 2014-06-02
...
201 2014-10-31
202 2014-12-05 --Missing a few dates
...
349 2015-04-29
350 2015-04-30
例如,我想在开始日期和结束日期之间按年份查找可用日期范围
@StartDate: 2014/04/06
@EndDate: 2015/04/05
预期结果是
Year StartRange EndRange
2014 2014-04-06 2014-05-20
2014 2014-06-01 2014-10-31
2014 2014-12-05 2014-12-31
2015 2015-01-01 2015-04-05
我正在尝试从“日期”列中查找可用的日期范围。让我们在预期结果 2014-04-06 到 2014-05-20 中取第一行,它说我有从 4 月 6 日到 5 月 20 日的连续日期,然后有一个休息时间(我没有从 2014-05-21 到 2014-05-30 的日期)
日期 2014-04-06(第一行)和 2015-04-05(最后一行)包含在预期结果中,因为它是开始日期和结束日期(查询参数),我在 table
的 [Dates] 列中有这些日期
谢谢
这是一个 "Islands and Gaps" 类型的问题。这是一种方法:
;
WITH
cteDays As (SELECT *, DATEDIFF(dd,0,Dates) As DayNo From YourTable)
, cteDifs As
(
SELECT *,
DayNo-(ROW_NUMBER() OVER(ORDER BY Dates, ID)) As Dif
FROM cteDays
)
SELECT
Year(Dates) As [Year],
MIN(Dates) As StartRange,
MAX(Dates) As EndRange
FROM cteDifs
GROUP BY Year(Dates), Dif
ORDER BY [Year], StartRange
我有一个 table 保存日期
ID Dates
1 2014-01-20
2 2014-01-21
...
100 2014-05-20
101 2014-06-01 --Missing a few dates
102 2014-06-02
...
201 2014-10-31
202 2014-12-05 --Missing a few dates
...
349 2015-04-29
350 2015-04-30
例如,我想在开始日期和结束日期之间按年份查找可用日期范围
@StartDate: 2014/04/06
@EndDate: 2015/04/05
预期结果是
Year StartRange EndRange
2014 2014-04-06 2014-05-20
2014 2014-06-01 2014-10-31
2014 2014-12-05 2014-12-31
2015 2015-01-01 2015-04-05
我正在尝试从“日期”列中查找可用的日期范围。让我们在预期结果 2014-04-06 到 2014-05-20 中取第一行,它说我有从 4 月 6 日到 5 月 20 日的连续日期,然后有一个休息时间(我没有从 2014-05-21 到 2014-05-30 的日期)
日期 2014-04-06(第一行)和 2015-04-05(最后一行)包含在预期结果中,因为它是开始日期和结束日期(查询参数),我在 table
的 [Dates] 列中有这些日期谢谢
这是一个 "Islands and Gaps" 类型的问题。这是一种方法:
;
WITH
cteDays As (SELECT *, DATEDIFF(dd,0,Dates) As DayNo From YourTable)
, cteDifs As
(
SELECT *,
DayNo-(ROW_NUMBER() OVER(ORDER BY Dates, ID)) As Dif
FROM cteDays
)
SELECT
Year(Dates) As [Year],
MIN(Dates) As StartRange,
MAX(Dates) As EndRange
FROM cteDifs
GROUP BY Year(Dates), Dif
ORDER BY [Year], StartRange