Sql server 连接SQL中的日期范围(首选T/SQL)
我需要将带有日期和代码的行连接到一个日期范围中 具有两列的表,这两列是复合主键日期和代码Sql server 连接SQL中的日期范围(首选T/SQL),sql-server,tsql,sql-server-2000,gaps-and-islands,Sql Server,Tsql,Sql Server 2000,Gaps And Islands,我需要将带有日期和代码的行连接到一个日期范围中 具有两列的表,这两列是复合主键日期和代码 Date Code 1/1/2011 A 1/2/2011 A 1/3/2011 A 1/1/2011 B 1/2/2011 B 2/1/2011 A 2/2/2011 A 2/27/2011 A 2/28/2011 A 3/1/2011 A 3/2/2011 A 3/3/2011 A 3/4/2011
Date Code
1/1/2011 A
1/2/2011 A
1/3/2011 A
1/1/2011 B
1/2/2011 B
2/1/2011 A
2/2/2011 A
2/27/2011 A
2/28/2011 A
3/1/2011 A
3/2/2011 A
3/3/2011 A
3/4/2011 A
需要转换为
Start Date End Date Code
1/1/2011 1/3/2011 A
2/1/2011 2/2/2011 A
1/1/2011 1/2/2011 B
2/27/2011 3/4/2011 A
还有其他方法吗?或者光标循环是唯一的方法吗?使用每月的DatePart函数将获得所需的组
SELECT Min(Date) as StartDate, Max(Date) as EndDate, Code
FROM ThisTable Group By DatePart(m, Date), Code
在month中使用DatePart函数将获得所需的组
SELECT Min(Date) as StartDate, Max(Date) as EndDate, Code
FROM ThisTable Group By DatePart(m, Date), Code
SQLServer2000有它的局限性。重写解决方案以使其更具可读性
declare @t table
(
[Date] datetime,
Code char(1)
)
insert into @T values
('1/1/2011','A'),
('1/2/2011','A'),
('1/3/2011','A'),
('1/1/2011','B'),
('1/2/2011','B'),
('3/1/2011','A'),
('3/2/2011','A'),
('3/3/2011','A'),
('3/4/2011','A')
select a.code, a.date, min(b.date)
from
(
select *
from @t t
where not exists (select 1 from @t where t.code = code and t.date -1 = date)
) a
join
(
select *
from @t t
where not exists (select 1 from @t where t.code = code and t.date = date -1)
) b
on a.code = b.code and a.date <= b.date
group by a.code, a.date
SQLServer2000有它的局限性。重写解决方案以使其更具可读性
declare @t table
(
[Date] datetime,
Code char(1)
)
insert into @T values
('1/1/2011','A'),
('1/2/2011','A'),
('1/3/2011','A'),
('1/1/2011','B'),
('1/2/2011','B'),
('3/1/2011','A'),
('3/2/2011','A'),
('3/3/2011','A'),
('3/4/2011','A')
select a.code, a.date, min(b.date)
from
(
select *
from @t t
where not exists (select 1 from @t where t.code = code and t.date -1 = date)
) a
join
(
select *
from @t t
where not exists (select 1 from @t where t.code = code and t.date = date -1)
) b
on a.code = b.code and a.date <= b.date
group by a.code, a.date
不幸的是,我陷入了SQL 2000的黑暗时代,但我会在获得测试/开发服务器设置后尽快尝试…@ggonsalv-对于SQL server 2000,我可能会使用游标。还有另一种使用子查询的方法,请参见此处,但性能确实很差。@ggonsalv-在等待服务器测试时,请在此处测试。不幸的是,我陷入了SQL 2000的黑暗时代,但我会在获得测试/开发服务器设置后尽快尝试…@ggonsalv-对于SQL server 2000,我可能会使用游标。还有另一种使用子查询的方法,请参见此处,但性能确实很差。@ggonsalv-在等待服务器测试时,请在此处测试。