Let say I've a table with a list of id/year/month (two years + 24 months for semplicity here):
Code Year Month
MAT000000001 2022 1
MAT000000001 2022 2
MAT000000001 2022 3
MAT000000001 2022 4
MAT000000001 2022 5
MAT000000001 2022 6
MAT000000001 2022 7
MAT000000001 2022 8
MAT000000001 2022 9
MAT000000001 2022 10
MAT000000001 2022 11
MAT000000001 2022 12
MAT000000001 2023 1
MAT000000001 2023 2
MAT000000001 2023 3
MAT000000001 2023 4
MAT000000001 2023 5
MAT000000001 2023 6
MAT000000001 2023 7
MAT000000001 2023 8
MAT000000001 2023 9
MAT000000001 2023 10
MAT000000001 2023 11
MAT000000001 2023 12
MAT000000002 2022 1
MAT000000002 2022 2
MAT000000002 2022 3
MAT000000002 2022 4
Also, I've this kind of History table:
CREATE TABLE [dbo].History(
[Id] [bigint] IDENTITY(1,1) NOT NULL,
[Code] [varchar](12) NOT NULL,
[DateStart] [datetime] NOT NULL,
[DateEnd] [datetime] NOT NULL,
CONSTRAINT [PK_ReferentiStorico] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
With data such as:
Id Code DateStart DateEnd
1 MAT000000001 1990-01-01 2023-03-31
2 MAT000000002 1990-01-01 9999-12-31
3 MAT000000001 2023-04-01 9999-12-31
Now, what I need to do is join the first table with the History, with the same Code and (and this is the heavy part) year month within the period described with DateStart and DateEnd.
In the example above, this must be the result:
Code Year Month HistoryId
MAT000000001 2022 1 1
MAT000000001 2022 2 1
MAT000000001 2022 3 1
MAT000000001 2022 4 1
MAT000000001 2022 5 1
MAT000000001 2022 6 1
MAT000000001 2022 7 1
MAT000000001 2022 8 1
MAT000000001 2022 9 1
MAT000000001 2022 10 1
MAT000000001 2022 11 1
MAT000000001 2022 12 1
MAT000000001 2023 1 1
MAT000000001 2023 2 1
MAT000000001 2023 3 1
MAT000000001 2023 4 3
MAT000000001 2023 5 3
MAT000000001 2023 6 3
MAT000000001 2023 7 3
MAT000000001 2023 8 3
MAT000000001 2023 9 3
MAT000000001 2023 10 3
MAT000000001 2023 11 3
MAT000000001 2023 12 3
MAT000000002 2022 1 2
MAT000000002 2022 2 2
MAT000000002 2022 3 2
MAT000000002 2022 4 2
Which the correct way to do this with SQL Server?
Not sure about the performance of this (i.e. create Date for every row):
inner join History as hist on ana.Code = hist.Code and datefromparts(initTable.Year, initTable.Month, 1) between hist.DateStart and hist.DateEnd