用最新值替换空值

时间:2017-04-12 11:25:27

标签: sql-server-2008 replace null

说我有下表。如果我的联合表格与日期和货币不匹配,我如何获取最新的先前值?在空DKK值上我想要它拿起3.请注意,由于我没有在周末加载表,因此每天都不存在日期。

Select
    PositionDate,
    Currency,
    T2.Value,
    isnull(t2.value, ? )
From t1
left join t2
on t1.currency = t2.Currency
and t1.PositionDate = t2.PositionDate

PositionDate    Currency        Value
2017-04-11      SEK               1
2017-04-11      DKK               NULL
2017-04-11      EUR               7
2017-04-10      SEK               4 
2017-04-10      DKK               3
2017-04-10      EUR               5
2017-04-07      SEK               4 
2017-04-07      DKK               3
2017-04-07      EUR               5

2 个答案:

答案 0 :(得分:0)

我认为这适合您的情况:

SELECT 
    t1.PositionDate,
    t1.Currency,
    COALESCE(t1.Value,t2.value) AS Value
FROM t1
LEFT join (SELECT MAX(PositionDate) AS PositionDate,Currency FROM t2 WHERE PositionDate < t1.PositionDate  GROUP BY Currency) tjoin
LEFT join t2 on tjoin.currency = t2.Currency and tjoin.PositionDate = t2.PositionDate

答案 1 :(得分:0)

您可以使用CTE和案例条件来实现它。

With cte as
(
    Select
        PositionDate,
        Currency,
        T2.Value,
    From t1
    left join t2
    on t1.currency = t2.Currency
    and t1.PositionDate = t2.PositionDate
        and t1.PositionDate = t2.PositionDate
)
select PositionDate, Currency, Value, 
   CASE WHEN ISNULL(value,'')='' THEN
    (Select top 1 from cte cin where cin.currency=cout.currency order by CONVERT(Date,PositionDate) desc)
   ELSE
    Value 
   END as Value2 
   From cte cout