我有两个具有以下结构的表:
DECLARE @Table1 TABLE
(
IdColumn INT,
DateColumn DATETIME
)
DECLARE @Table2 TABLE
(
IdColumn INT,
DateColumn DATETIME,
Value NUMERIC(18,2)
)
我想要做的是从 table2 中获取最新值,在 table1 中具有更少或相等的日期。
这是我建立的查询:
SET NOCOUNT ON
DECLARE @Table1 TABLE
(
IdColumn INT,
DateColumn DATETIME
)
DECLARE @Table2 TABLE
(
IdColumn INT,
DateColumn DATETIME,
Value NUMERIC(18,2)
)
DECLARE @RefDate DATETIME='2012-09-01'
DECLARE @NMonths INT
DECLARE @MonthsCounter INT=1
SELECT @NMonths=DATEDIFF(MM,'2012-09-01','2013-03-01')
WHILE @MonthsCounter<=@NMonths
BEGIN
INSERT INTO @Table1
SELECT 1,@RefDate
SET @RefDate=DATEADD(MM,1,@RefDate);
SET @MonthsCounter+=1;
END
INSERT @Table2
SELECT 1,'2012-09-01',1000
UNION
SELECT 1,'2012-12-01',5000
UNION
SELECT 1,'2013-01-01',3000
SELECT
T1.IdColumn,
T1.DateColumn,
T2.Value
FROM @Table1 T1
LEFT JOIN @Table2 T2
ON T2.IdColumn=T1.IdColumn AND T1.DateColumn>=t2.DateColumn
问题是当一个新值带有一个更新的日期时,我会得到该日期之前的所有值。
IdColumn DateColumn Value
----------- ----------------------- ---------------------------------------
1 2012-09-01 00:00:00.000 1000.00
1 2012-10-01 00:00:00.000 1000.00
1 2012-11-01 00:00:00.000 1000.00
1 2012-12-01 00:00:00.000 1000.00
1 2012-12-01 00:00:00.000 5000.00
1 2013-01-01 00:00:00.000 1000.00
1 2013-01-01 00:00:00.000 5000.00
1 2013-01-01 00:00:00.000 3000.00
1 2013-02-01 00:00:00.000 1000.00
1 2013-02-01 00:00:00.000 5000.00
1 2013-02-01 00:00:00.000 3000.00
所需的输出是这个:
IdColumn DateColumn Value
----------- ----------------------- ---------------------------------------
1 2012-09-01 00:00:00.000 1000.00
1 2012-10-01 00:00:00.000 1000.00
1 2012-11-01 00:00:00.000 1000.00
1 2012-12-01 00:00:00.000 5000.00
1 2013-01-01 00:00:00.000 3000.00
1 2013-02-01 00:00:00.000 3000.00
我该如何解决这个问题?
谢谢。