开发者

SQL Query Start and End Date

开发者 https://www.devze.com 2023-04-02 03:42 出处:网络
This is slightly different than开发者_Go百科 this: SQL Query Creating Start and End Dates And I do not know how to phrase this question as I suck in English.

This is slightly different than开发者_Go百科 this: SQL Query Creating Start and End Dates

And I do not know how to phrase this question as I suck in English.

Table

Name | Date
Foo | 1-Sep
Foo | 2-Sep
Foo | 3-Sep
Foo | 5-Sep
Foo | 6-Sep
Foo | 7-Sep

Foo | 1-Dec
Foo | 2-Dec

Foo | 4-Dec
Foo | 5-Dec
Foo | 6-Dec
Foo | 7-Dec
Foo | 8-Dec

Foo | 1-Feb

Foo | 14-Feb
Foo | 15-Feb
Foo | 16-Feb
Foo | 17-Feb
Foo | 18-Feb
Foo | 19-Feb
Foo | 20-Feb

Foo | 22-Feb

I need to create a query with the below result

Query Result

Name | Start Date  |  End Date
Foo  |  1-Sep      | 3-Sep
Foo  |  5-Sep      | 7-Sep
Foo  |  4-Dec      | 8-Dec
Foo  |  1-Feb      | 1-Feb
Foo  |  1-Dec      | 2-Dec
Foo  |  14-Feb     | 20-Feb
Foo  |  22-Feb     | 22-Feb

Update:

  • Start Date: First day of a series of consecutive days
  • End Date: Last day of a series of consecutive days
  • If a date is not included in a series of consecutive days, like Feb 22 above, it is the start and end date.


Not sure if its the best way. You can first filter all dates that have previous and next day, then you can use solution explained in here

Query that filters unimportant dates:

select t1.Name, t.Date from Table t1
left outer join Table t2 on dateadd(d,-1,t1.Date) = t2.Date 
left outer join Table t3 on dateadd(d,1,t1.Date) = t3.Date
where t2.Date is null or t3.Date is null 
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号