2017-04-12 17 views
0

以下の表があります。結合したテーブルが日付と通貨と一致しない場合は、どのようにして最新の以前の値を取得するのですか?ヌルのDKK値では、私はそれを拾いたい3。私は週末にテーブルを読み込まないので、日付は毎日存在しないことに注意してください。null値を最新の値に置き換えてください。

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 

答えて

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 
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 
関連する問題