如何选择过去 13 个月的数据?

时间:2021-03-05 11:01:56

标签: sql sql-server select

我有两个结构完全相同的表

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.

现在我需要“联合所有”这两个表,并且每次运行查询时只需要最近 13 个月的数据

Select * from Data_2020 
union all
select * from Data_2021

我必须每个月运行一次,并且只需要最近 13 个月的数据。如何应用过滤器?我在两个表中都有一个日期列“日期”。

2 个答案:

答案 0 :(得分:0)

如果要考虑表中的日期列以获取当前最大日期,可以使用此查询

DECLARE @CurrentMaxDate DATE
SET @CurrentMaxDate = (SELECT Top 1 [Date] FROM Data_2021 ORDER BY [Date] DESC)
;WITH TempCTE AS (
SELECT * FROM Data_2020 
UNION ALL
SELECT * FROM Data_2021
)
SELECT * FROM TempCTE
WHERE [Date] > DATEADD(Month,-13, @CurrentMaxDate)

答案 1 :(得分:0)

onDestroy
相关问题