没有循环或光标,如何将日期间隔列表转换为一串0和1的字符串,使得:
- 每个位表示从所有日期中的最小值到最大值的每一天
- 如果该天在任何一个日期间隔内,则该位为1
- 如果该天不在任何一个日期间隔内,则该位为0
例如,如果区间是:
- 2011年1月1日至2011年1月2日
- 2011年1月4日至2011年1月5日
那么你编写的SQL应该输出11011。以下是您可以使用的设置脚本:
declare @TimeSpan table
(
start datetime
,finish datetime
)
-- this is a good data set, with overlapping and non-overlapping time spans
insert into @TimeSpan values ('02/02/2010', '02/02/2010')
insert into @TimeSpan values ('02/03/2010', '02/03/2010')
insert into @TimeSpan values ('02/04/2010', '02/05/2010')
insert into @TimeSpan values ('02/05/2010', '02/06/2010')
insert into @TimeSpan values ('02/07/2010', '02/09/2010')
insert into @TimeSpan values ('02/08/2010', '02/08/2010')
insert into @TimeSpan values ('02/08/2010', '02/10/2010')
insert into @TimeSpan values ('02/14/2010', '02/16/2010')
-- for this set of data, the output string would be 111111111000111