简体   繁体   English

可用日期范围(按年份)

[英]Available date range by year

I have a table that holds date 我有一张桌子,上面放着日期

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

I want to find the available date range by year between a from and to date, for example 我想按年份查找从日期到日期之间的可用日期范围,例如

@StartDate: 2014/04/06
@EndDate: 2015/04/05

The expected result is 预期的结果是

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

I am trying to find the available date ranges from the Dates column. 我正在尝试从日期列中找到可用的日期范围。 Lets take the first row in the expected result 2014-04-06 to 2014-05-20 which says I have continuous dates from the 6th April to 20th May then there is a break (I do not have dates from 2014-05-21 to 2014-05-30) 让我们在预期结果2014-04-06至2014-05-20的第一行中说,我从4月6日到5月20日有连续的日期,然后有一个休息时间(我没有从2014-05-21开始的日期至2014-05-30)

The dates 2014-04-06 (in the first row) and 2015-04-05 (in the last row) are included in the expected result as it is the start and end date (parameter to the query) and I have those dates in the [Dates] column of my table 日期2014-04-06 (在第一行)和2015-04-05 (在最后一行)包含在预期结果中,因为它是开始和结束日期(查询的参数),我拥有这些日期在我表格的[日期]栏中

Thanks 谢谢

This is an "Islands and Gaps" type of problem. 这是“孤岛和差距”类型的问题。 Here is one way to do it: 这是一种实现方法:

;
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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM