如何从最多日期
的3个表中获取数据select
c.model_key, v.id, v.category_Id, v.Text1, v.Numeric1,
c.Name, fx.Currency_code, fx.Rate, fx.effective_dt
from
aps.v_m_fxrates fx
join
aps.t_m_value v on fx.Currency_code = v.Text1
join
aps.t_m_category c on v.Category_Id = c.Id
where
c.Name = 'FXRates'
and c.Model_Key = 25
and v.Text1 = fx.Currency_code
and fx.version = 2
使用上面的查询我得到了结果,但结果出现在所有effective_dt
上。而不是这个,我只需要选择最新effective_dt
的记录。在下图中,有2条AED记录,其中最新日期为1999-03-31,必须返回。在此之后我不知道如何继续并进一步过滤结果以实现输出。
我也试过这个
select
c.model_key, v.id, v.category_Id, v.Numeric1,
c.Name, fx.Currency_code, fx.Rate, fx.effective_dt
from
aps.v_m_fxrates fx
join
aps.t_m_value v on fx.Currency_code = v.Text1
join
aps.t_m_category c on v.Category_Id = c.Id
where
c.Name = 'FXRates'
and c.Model_Key = 25
and v.Text1 = fx.Currency_code
and fx.version = 2
and fx.effective_dt in (select MAX(effective_dt)
from aps.v_m_fxrates)
但没有回复。
实际输出:
预期产出:
答案 0 :(得分:1)
在子查询中使用 row_number() 函数,如下所示:
select
c.model_key, v.id, v.category_Id, v.Text1, v.Numeric1,
c.Name, fx.Currency_code, fx.Rate, fx.effective_dt
from (
select
Currency_code,Rate,effective_dt
,SeqNo = row_number() over (partition by Currency_code order by effective_dt desc)
from aps.v_m_fxrates
where version = 2
) fx
join
aps.t_m_value v on fx.Currency_code = v.Text1
join
aps.t_m_category c on v.Category_Id = c.Id
where c.Name = 'FXRates'
and c.Model_Key = 25
and v.Text1 = fx.Currency_code
and fx.SeqNo = 1
答案 1 :(得分:0)
尝试使用运算符 TOP 1 和相应的 ORDER BY
例如:
SELECT TOP 1 C.model_key,
V.id,
...
FROM ...
ORDER BY FX.effective_dt DESC
您拥有的另一个选项是在where子句中使用聚合函数和相关性。
select C.model_key,
V.id,
V.category_Id,
V.Text1,
V.Numeric1,
C.Name,
FX.Currency_code,
FX.Rate,
FX.effective_dt
FROM aps.v_m_fxrates AS FX
JOIN aps.t_m_value AS V on FX.Currency_code = V.Text1
JOIN aps.t_m_category AS C on V.Category_Id = C.Id
WHERE C.Name = 'FXRates'
AND C.Model_Key = 25
AND FX.version = 2
AND FX.effective_dt =
(SELECT MAX(effective_dt) FROM aps.v_m_fxrates AS FX2
WHERE FX2.currency_code = FX.currency_code)
答案 2 :(得分:0)
select
c.model_key, v.id,v.category_Id, v.Numeric1,
c.Name, fx.Currency_code, fx.Rate, fx.effective_dt
from
aps.v_m_fxrates fx
join
aps.t_m_value v on fx.Currency_code = v.Text1
join
aps.t_m_category c on v.Category_Id = c.Id
where
c.Name = 'FXRates'
and c.Model_Key = 25
and v.Text1 = fx.Currency_code
and fx.version = 2
and fx.effective_dt = (select MAX(effective_dt) from aps.v_m_fxrates)
试试这个;您使用了fx.effective_dt in
,但您必须使用=
,因为您需要最大日期记录。使用=
后,它只会返回一行。