我有两个具有以下结构的表:
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
我该如何解决这个问题?
感谢。
答案 0 :(得分:2)
我只是用正确的语法发布戈登的答案:
select t1.*,
(select top 1 value
from @table2 t2
where t2.IdColumn = t1.IdColumn and
t2.DateColumn <= t1.DateColumn
order by t2.DateColumn desc
) t2value
from @table1 t1
答案 1 :(得分:1)
我会使用相关子查询来执行此操作:
select t1.*,
(select top 1 value
from @table2 t2
where t2.idColumn = t1.idColumn and
t2.dateColumn <= t1.dateColumn
order by t2.dateColumn desc
) t2value
from @table1 t1;
答案 2 :(得分:0)
评论后,试试这个:
INSERT INTO #Table1 (IdColumn, DateColumn)
SELECT IdColumn, DateColumn
FROM #Table2 t
WHERE NOT EXISTS
(
SELECT 'X'
FROM #Table2 tcopy
where t.IdColumn = tcopy.IdColumn
and convert(date, t.DateColumn) = convert(date, tcopy.DateColumn)
and tCopy.DateColumn > t.DateColumn
)
我用过“&gt;”因为你告诉我,你的table2中没有相同日期/时间的行