Using SQL Server 2008 and a set based solution, how could I manipulate the following data:
GroupID Code StartSeq EndSeq StartDayNo EndDayNo
1755549 3506 0 0 59442 59444
1755549 2928 1 3 59444 59465
1755549 2928 4 5 59465 59467
1755549 2928 6 6 59467 59481
1755549 2928 7 8 59481 59482
1755549 2928 9 9 59482 59494
1755549 3429 10 10 59494 59494
1755549 2928 11 11 59494 59496
1755549 3429 12 12 59496 59496
1755549 2928 13 13 59496 59501
To get this result:
GroupID Code StartSeq EndSeq StartDayNo EndDayNo
1755549 3506 0 0 59442 59444
1755549 2928 1 9 59444 59494
1755549 3429 10 10 59494 59494
1755549 2928 11 11 59494 59496
1755549 3429 12 12 59496 59496
1755549 2928 13 13 59496 59501
The query I originally came up with would only group together 2 rows by using a join, in the example there are 5 rows that need to be grouped to only one.
Script below with some sample data. Note there is additional data than the original example.
DECLARE @SampleData TABLE (
[GroupID] [int] NOT NULL,
[Code] [varchar](4) NOT NULL,
[StartSeq] [int] NOT NULL,
[EndSeq] [int] NOT NULL,
[StartDayNo] [int] NOT NULL,
[EndDayNo] [int] NOT NULL
)
INSERT INTO @SampleData
VALUES
(1622494, N'2082', 0, 0, 59136, 59137)
, (1622494, N'2082', 1, 1, 59137, 59167)
, (1622494, N'2934', 2, 2, 59167, 59335)
, (1622494, N'3613', 3, 3, 59335, 59350)
, (1755549, N'3506', 0, 0, 59442, 59444)
, (1755549, N'2928', 1, 3, 59444, 59465)
, (1755549, N'2928', 4, 5, 59465, 59467)
, (1755549, N'2928', 6, 6, 59467, 59481)
, (1755549, N'2928', 7, 8, 59481, 59482)
, (1755549, N'2928', 9, 9, 59482, 59494)
, (1755549, N'3429', 10, 10, 59494, 59494)
, (1755549, N'2928', 11, 11, 59494, 59496)
, (1755549, N'3429', 12, 12, 59496, 59496)
, (1755549, N'2928', 13, 13, 59496, 59501)

StartSeqvalues guaranteed to be consecutive? – ypercube Jan 25 at 15:43StartSeqbut theEndSeqcould any number >=0. So theEndSeqfor the first record could be 4 and theStartSeqfor the next record in thatGroupIDwould be 5. – djphatic Jan 25 at 15:53