Skip to content
Advertisement

How can I select data from last 13 months?

I have two tables with exactly same structure

table 1 - Data_2020 --> This is an static table which has data from year 2020 and is not being updated anymore (archive table). It has around 4 million records
table 2 - Data_2021 --> This is my current table which is increasing everyday. It has currently 0.8 million records but it will increase till December.

Now I need to ‘union all’ these two tables and I want only last 13 month data every time I run below query

Select * from Data_2020 
union all
select * from Data_2021

I have to run this every month and need only last 13 month data. How can I apply the filter? I have a date column ‘date’ in both the tables.

Advertisement

Answer

declare @StartDate datetime,@CurrentDate datetime
set @CurrentDate = GETDATE();
set @StartDate = DATEADD(MONTH,-13,@CurrentDate)


SELECT *
FROM Data_2020
WHERE DateFieldName > @StartDate -- Or DateFieldName BETWEEN @StartDate AND @CurrentDate
UNION ALL
SELECT *
FROM Data_2021
WHERE DateFieldName > @StartDate -- Or DateFieldName BETWEEN @StartDate AND @CurrentDate
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement