I have follwing data :
Product Price StartDate EndDate
Apples 4.9 2010-03-01 00:00:00.000 2010-03-01 00:00:00.000
Apples 4.9
I believe this is the best-performing solution so far:
WITH Calc AS (
SELECT *,
Grp = DateAdd(day, -Row_Number()
OVER (PARTITION BY Product, Price ORDER BY StartDate), StartDate
)
FROM dbo.PriceHistory
)
SELECT Product, Price, FromDate = Min(StartDate), ToDate = Max(StartDate)
FROM Calc
GROUP BY Product, Price, Grp
ORDER BY FromDate;
Try this out yourself