SQL存储过程最大日期问题

时间:2012-02-23 12:10:34

标签: sql stored-procedures maxdate

我遇到了从存储过程中获取MAX DATE的问题。

基本上,我有一个包含捕获日期的汇率列表,这些列表每天都存储在一个表格中,我希望返回最新值。

以下是我正在处理的代码..

select  
distinct t.source_currency_code, t.target_currency_code,
'(' + t.source_currency_code + ') '  + s.currency_name as source_currency_name, 
'(' + t.target_currency_code + ') '  + x.currency_name as target_currency_name,
t.converted_amount as buy_rate,
t.date_loaded as date_loaded

from texchange_rate t, tcurrency s, tcurrency x

where 
s.currency_code = t.source_currency_code and 
x.currency_code = t.target_currency_code

order by  t.source_currency_code

我的想法是MAX(.t.date_loaded按货币代码分组),但这不起作用......

感谢任何帮助!

2 个答案:

答案 0 :(得分:2)

我认为你需要有源和目标货币作为查找最新购买率的元素。

你能和他相处吗?

 SELECT
t.source_currency_code, t.target_currency_code,
'(' + t.source_currency_code + ') '  + s.currency_name as source_currency_name, 
'(' + t.target_currency_code + ') '  + x.currency_name as target_currency_name,
t.converted_amount as buy_rate,
t.date_loaded as date_loaded
FROM 
texchange_rate t
INNER JOIN tcurrency s
ON t.source_currency_code = s.currency_code
INNER JOIN tcurrency x
ON t.target_currency_code = x.currency_code
WHERE t.date_loaded in 
      (
          SELECT max(date_loaded) from texchange_rate tt
          where t.source_currency_code = tt.source_currency_code
          and t.target_currency_code = tt.target_currency_code
      )
order by date_loaded desc

<强>更新 删除distinct和group by货币代码,我认为按date_loaded的顺序会给你最新的值,不知道这是不是你想要的。

答案 1 :(得分:1)

尝试:

select * from 
(select t.source_currency_code, 
        t.target_currency_code,
        '('+t.source_currency_code+') '  + s.currency_name as source_currency_name, 
        '('+t.target_currency_code+') '  + x.currency_name as target_currency_name,
        t.converted_amount as buy_rate,
        t.date_loaded as date_loaded,
        rank() over (partition by t.source_currency_code, 
                                  t.target_currency_code 
                     order by t.date_loaded desc) rn
 from texchange_rate t
 join tcurrency s on s.currency_code = t.source_currency_code 
 join tcurrency x on x.currency_code = t.target_currency_code) v
where rn = 1
order by source_currency_code, target_currency_code
相关问题