我假设(也许是粗鲁地)您的样本数据包含错误,并且范围应该是 2000、2002-2003 和 2005,因为没有 2001 或 2004 的模型。如果我是对的,那么这将起作用:
WITH CTE AS
( SELECT Cars.CarMake,
Cars.CarModel,
[FirstYear] = Cars.CarYear,
[LastYear] = Cars.CarYear,
[Recursion] = 1
FROM Cars
UNION ALL
SELECT CTE.CarMake,
CTE.CarModel,
CTE.[FirstYear],
[LastYear] = Cars.CarYear,
[Recursion] = [Recursion] + 1
FROM CTE
INNER JOIN Cars
ON CTE.CarMake = Cars.CarMake
AND CTE.CarModel = Cars.CarModel
AND CTE.[LastYear] = Cars.CarYear - 1
), MaxCTE AS
( SELECT CarMake,
CarModel,
FirstYear,
LastYear,
Recursion,
[MaxRecursion] = MAX(Recursion) OVER(PARTITION BY CarMake, CarModel, FirstYear)
FROM CTE
)
SELECT MaxCTE.CarMake,
MaxCTE.CarModel,
[CarYearRange] = CAST(FirstYear AS VARCHAR(4)) + ' - ' + CAST(LastYear AS VARCHAR(4))
FROM MaxCTE
WHERE Recursion = MaxRecursion
AND NOT EXISTS
( SELECT 1
FROM MaxCTE ex
WHERE MaxCTE.CarMake = ex.CarMake
AND MaxCTE.CarModel = ex.CarModel
AND MaxCTE.FirstYear > ex.FirstYear
AND MaxCTE.LastYear = ex.LastYear
)
SQL 小提琴示例
编辑
如果我正确解释了要求,请使用 RICHARD THE KIWI 的回答。它比我的好多了!
小提琴改进的解决方案
SELECT CarMake,
CarModel,
[StartYear] = MIN(CarYear),
[EndYear] = MAX(CarYear)
FROM ( SELECT *,
[Offset] = CarYear - ROW_NUMBER() OVER (PARTITION BY CarMake, CarModel ORDER BY CarYear)
FROM Cars
) x
GROUP BY CarMake, CarModel, Offset
ORDER BY CarMake, CarModel, StartYear