Sql server 2008 用最新值替换空值
说我有下面的表格。如果我的联接表与日期和货币不匹配,如何提取上一个最新值?在空DKK值上,我希望它拾取3。请注意,日期并非每天都存在,因为我不会在周末加载表Sql server 2008 用最新值替换空值,sql-server-2008,replace,null,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 .我认
Select
PositionDate,
Currency,
T2.Value,
isnull(t2.value, ? )
From t1
left join t2
on t1.currency = t2.Currency
and t1.PositionDate = t2.PositionDate
.我认为这对你的情况很有效:
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
您可以通过使用CTE和Case条件来实现它
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
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