我不能拿出任何短使用光標。但是,這確實有效:
declare @example table (tKey int, Valid int, DateFrom date, DateTo date);
insert into @example values (1, 0, '2001-01-01', '2001-01-31');
insert into @example values (1, 0, '2001-02-01', '2001-02-20');
insert into @example values (1, 1, '2001-02-21', '2001-02-28');
insert into @example values (1, 0, '2001-03-01', '2001-03-15');
insert into @example values (2, 1, '2001-01-01', '2001-01-31');
insert into @example values (2, 0, '2001-02-01', '2001-02-20');
insert into @example values (2, 0, '2001-02-21', '2001-02-28');
insert into @example values (2, 1, '2001-03-01', '2001-03-15');
declare @output table (tKey int, Valid int, DateFrom date, DateTo date);
DECLARE ex_cursor CURSOR FOR
select
tKey,Valid,DateFrom,DateTo
from
@example
order by tKey, DateFrom
DECLARE @tKey int
DECLARE @Valid int
DECLARE @DateFrom date
DECLARE @DateTo date
DECLARE @last_tKey int
DECLARE @last_Valid int
DECLARE @min_Date date
DECLARE @max_Date date
OPEN ex_cursor;
FETCH NEXT FROM ex_cursor
INTO @tKey, @Valid, @DateFrom, @DateTo;
SET @last_tKey = @tKey;
SET @last_Valid = @Valid;
SET @min_Date = @DateFrom;
SET @max_Date = @DateTo;
WHILE @@FETCH_STATUS = 0
BEGIN
IF (@last_tKey <> @tKey OR @last_Valid <> @Valid)
BEGIN
-- output results
INSERT INTO @output SELECT @last_tKey, @last_Valid, @min_Date, @max_Date
-- reset values
SET @last_tKey = @tKey;
SET @last_Valid = @Valid;
SET @min_Date = @DateFrom;
SET @max_Date = @DateTo;
END
ELSE
BEGIN
IF (@DateTo > @max_Date) SET @max_Date = @DateTo
END
FETCH NEXT FROM ex_cursor
INTO @tKey, @Valid, @DateFrom, @DateTo
END
-- output one more time at end
INSERT INTO @output SELECT @last_tKey, @last_Valid, @min_Date, @max_Date
CLOSE ex_cursor;
DEALLOCATE ex_cursor;
SELECT * FROM @output ORDER BY tKey, DateFrom
您的源數據中是否存在任何間隙或重疊? – MatBailie
你可以使用任何提供的解決方案嗎? –
是的,現在回答 - 感謝大家的建議 - 非常感謝 – BennyD