基于开始和结束年份的一对多结果集

时间:2019-04-05 01:29:19

标签: sql-server tsql

我正在尝试根据下表返回一个结果集,其中将包括每辆车的品牌,型号,描述和年份。我不了解的部分是给定席位在开始和结束年之间每年返回一行。

例如,如果座位运行2002-2008,我想返回2002、2003、2004 ...的行...

制作: MakeId,MakeName

型号: ModelId,MakeId,ModelName

座位: SeatId,ModelId,StartYear,EndYear,说明

当前单行查询如下:

SELECT Make.MakeName, Model.ModelName, Seats.StartYear, Seats.EndYear, Seats.Description
FROM Make
INNER JOIN Model ON Make.MakeId = Model.MakeId
INNER JOIN Seats ON Seats.ModelId = Model.ModelId

谢谢!

1 个答案:

答案 0 :(得分:0)

DECLARE @MIN_YEAR INTEGER = (SELECT MIN(StartYear) FROM [dbo].[Seats]);
DECLARE @MAX_YEAR INTEGER = (SELECT MAX(EndYear) FROM [dbo].[Seats]);

WITH CTE AS (
    SELECT @MIN_YEAR AS Year
    UNION ALL
    SELECT Year + 1 FROM CTE
    WHERE Year < @MAX_YEAR
)
SELECT Make.MakeName, Model.ModelName, Seats.StartYear, Seats.EndYear, 
Seats.Description
FROM Make
INNER JOIN Model ON Make.MakeId = Model.MakeId
INNER JOIN Seats ON Seats.ModelId = Model.ModelId
CROSS APPLY ( SELECT * FROM CTE WHERE Year BETWEEN Seats.StartYear AND Seats.EndYear ) T 
OPTION
(
    MAXRECURSION 0
)