0

我有两个具有以下结构的表:

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

我该如何解决这个问题?

谢谢。

4

3 回答 3

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
于 2013-07-30T12:47:23.237 回答
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;
于 2013-07-30T12:33:00.337 回答
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
    )

我使用“>”是因为您告诉我,您的 table2 中没有具有相同日期/时间的行

于 2013-07-30T13:14:31.577 回答