我有一个包含时间段的表
StartDate CancelDate
2014-01-01 00:00:00.000 2014-01-15 00:00:00.000
2014-01-16 00:00:00.000 2014-01-31 00:00:00.000
2014-02-05 00:00:00.000 2014-02-15 00:00:00.000
您可以看到前两行中的句点已连接,并且它们正在创建从2014-01-01
到2014-01-31
的一个更大的句点,并且在第三行中有一段未连接的句点。
如何从上面的表中获取此表?
StartDate CancelDate
2014-01-01 00:00:00.000 2014-01-31 00:00:00.000
2014-02-05 00:00:00.000 2014-02-15 00:00:00.000
答案 0 :(得分:1)
这些方面的内容应该有效:
SELECT MIN(startdate) StartDate, CancelDate
FROM
(
SELECT a.startdate,
COALESCE(b.canceldate, a.canceldate) canceldate
FROM dt a
LEFT JOIN dt b ON
(b.startdate=DATEADD(d,1,a.canceldate) OR a.canceldate=b.startdate)
) x
GROUP BY CancelDate
dt是您的数据表
答案 1 :(得分:0)
declare @t table (start VARCHAR(10),enddate VARCHAR(10))
insert into @t (start,enddate)values
('2014-01-01','2014-01-15'),
('2012-01-01','2012-01-15'),
('2014-01-15','2014-01-31'),
('2014-02-02','2014-02-15'),
('2014-02-15','2014-02-28')
Select MIN(CAST (start AS DATE)),MAX(CAST (enddate AS DATE))
from @t
group by LEFT(start,7),LEFT(enddate,7)
或使用CTE
;WITH CTE AS
(
select DISTINCT
(select min(start) from @t
where LEFT(start,7) = LEFT(m.start,7)
) as StartDate,
(select max(enddate) from @t
where LEFT(enddate,7) = LEFT(m.enddate,7)
) as EndDate,
ROW_NUMBER()OVER(PARTITION BY LEFT(STart,7) ORDER BY LEFT(STart,7) DESC)RN
from
@t m
)
Select DISTINCT StartDate,EndDate from CTE