Вы можете попробовать это
DECLARE @Occurrence TABLE(
OccurrenceID INT,
OccurrenceBucketID INT,
OccurrenceTime DATETIME,
OccurrenceMessage VARCHAR(MAX)
)
INSERT INTO @Occurrence (OccurrenceID,OccurrenceBucketID,OccurrenceTime,OccurrenceMessage)
SELECT 1, 1, '01 Jan 2009', 'A'
INSERT INTO @Occurrence (OccurrenceID,OccurrenceBucketID,OccurrenceTime,OccurrenceMessage)
SELECT 2, 1, '02 Jan 2009', 'B'
INSERT INTO @Occurrence (OccurrenceID,OccurrenceBucketID,OccurrenceTime,OccurrenceMessage)
SELECT 3, 1, '03 Jan 2009', 'C'
INSERT INTO @Occurrence (OccurrenceID,OccurrenceBucketID,OccurrenceTime,OccurrenceMessage)
SELECT 4, 2, '04 Jan 2009', 'D'
INSERT INTO @Occurrence (OccurrenceID,OccurrenceBucketID,OccurrenceTime,OccurrenceMessage)
SELECT 5, 2, '05 Jan 2009', 'E'
INSERT INTO @Occurrence (OccurrenceID,OccurrenceBucketID,OccurrenceTime,OccurrenceMessage)
SELECT 6, 2, '06 Jan 2009', 'F'
SELECT * FROM @Occurrence
DECLARE @OccurrenceBucket TABLE(
OccurrenceBucketID INT,
FirstOccurrenceID INT,
FirstOccurrenceTime DATETIME,
FirstOccurrenceMessage VARCHAR(MAX)
)
INSERT INTO @OccurrenceBucket (OccurrenceBucketID) SELECT 1
INSERT INTO @OccurrenceBucket (OccurrenceBucketID) SELECT 2
SELECT * FROM @OccurrenceBucket
UPDATE @OccurrenceBucket
SET FirstOccurrenceID = OccurrenceID,
FirstOccurrenceTime = OccurrenceTime,
FirstOccurrenceMessage = OccurrenceMessage
FROM @OccurrenceBucket oc INNER JOIN
(
SELECT o.*
FROM @Occurrence o INNER JOIN
(
SELECT OccurrenceBucketID,
MIN(OccurrenceID) FirstOccurrenceID
FROM @Occurrence
GROUP BY OccurrenceBucketID
) Mins ON o.OccurrenceID = mins.FirstOccurrenceID
) Vals ON oc.OccurrenceBucketID = Vals.OccurrenceBucketID
SELECT * FROM @OccurrenceBucket
EDIT:
UPDATE @OccurrenceBucket
SET FirstOccurrenceID = OccurrenceID,
FirstOccurrenceTime = OccurrenceTime,
FirstOccurrenceMessage = OccurrenceMessage
FROM @OccurrenceBucket oc INNER JOIN
(
SELECT o.*
FROM @Occurrence o INNER JOIN
(
SELECT OccurrenceBucketID,
MIN(OccurrenceTime) FirstOccurrenceTime
FROM @Occurrence
GROUP BY OccurrenceBucketID
) Mins ON o.OccurrenceTime = mins.FirstOccurrenceTime
) Vals ON oc.OccurrenceBucketID = Vals.OccurrenceBucketID