货币换算 - 实际和最新可用日期

时间:2014-09-20 07:48:03

标签: sql ms-access

我有一个我无法解决的SQL问题,所以任何帮助都会非常感激。我正在创建一个数据库,用于跟踪公司的不同货币的工作。我每天都报告工作和每月货币转换,这很好。对于那些我需要使用最新可用汇率的人来说,我的问题是预计未来的结算日期。我怎样才能编写一个SQL,以便在将来结算日期时,它会选择最新的,否则需要正确的月份?我尝试过使用CASE和子查询,但还是找不到解决方案。我正在使用MS Access完成这项工作。

我当前的SQL有效但由于内部联接而无法获取未来日期,如下所示

SELECT jobs.ProjectName, jobs.[NetFee]*Exch.[CurrencyRate] AS 
FROM tblJobs AS Jobs 
INNER JOIN tblExchangeRate AS Exch
ON Jobs.CurrencyID = Exch.CurrencyID
AND Year(Jobs.[BillDate]) = Year(Exch.[CurrencyDate])
AND Month(Jobs.[BillDate]) = Year(Exch.[CurrencyDate]);

涉及的字段和表格具有以下结构

tblExchangeRate(每月数据)

ID    CurrencyID    ExchangeRate    CurrencyDate
1     1             1.50            2005-01-31
2     1             1.52            2005-02-28
.
.
x     x             1.63            2014-08-30

tblJobs

ID    ProjectName    NetFee    CurrencyID    BillDate
1     AA             100       1             2010-01-15
2     BB             200       2             2015-04-20
.
.

2 个答案:

答案 0 :(得分:0)

首次查询
 对于其结算日期未来的项目  在此查询中,我们从tblExchangeRate中的正确月份获取ExchangeRate。

第二次查询
 对于其结算日期未来的项目
在此查询中,我们从MaxExch(子查询)获取ExchangeRate。
(MaxExch:为每个CurrencyID选择最新的ExchangeRate的子查询。)

解决方案 首先查询 联盟 secondQuery

(SELECT jobs.ProjectName AS PN, jobs.[NetFee]*Exch.[ExchangeRate] AS M
FROM tblJobs AS Jobs , tblExchangeRate AS Exch
WHERHE Jobs.CurrencyID = Exch.CurrencyID
       AND Year(Jobs.[BillDate]) = Year(Exch.[CurrencyDate])
       AND Month(Jobs.[BillDate]) = Year(Exch.[CurrencyDate])
)
UNION
(SELECT jobs.ProjectName AS PN, jobs.[NetFee]*MaxExch.[ExchangeRate] AS M
 FROM tblJobs AS Jobs , (SELECT CurrencyID, ExchangeRate, CurrencyDate
                         FROM tblJobs tb1
                         WHERE CurrencyDate = (SELECT MAX(CurrencyDate) FROM tblJobs t2
                                               WHERE t2.CurrencyID =t1.CurrencyID )
                         ) MaxExch
 WHERE Jobs.BillDate > MaxExch.CurrencyDate AND Jobs.CurrencyID= MaxExch.CurrencyID);

答案 1 :(得分:0)

'我尝试过使用... CASE ...我正在使用MS Access完成这项工作。'嗯,如果它的访问权限一直在下降'那么问题的一部分是Access SQL不支持CASE(它有IIF)。那说,怎么样:

SELECT jobs.ProjectName, jobs.NetFee * IIF(Exch.CurrencyRate Is Null,
                         LatestExch.CurrencyRate, Exch.CurrencyRate) AS M
FROM (tblJobs AS Jobs 
INNER JOIN (
    SELECT lcr.CurrencyID, lcr.CurrencyRate
    FROM tblExchangeRate lcr
    INNER JOIN (
        SELECT lcd.CurrencyID, MAX(lcd.CurrencyDate) AS CurrencyDate
        FROM tblExchangeRate AS lcd
        GROUP BY lcd.CurrencyID) AS lcd
    ON lcr.CurrencyID = lcd.CurrencyID AND lcr.CurrencyDate = lcd.CurrencyDate) AS LatestExch
ON Jobs.CurrencyID = LatestExch.CurrencyID )
LEFT JOIN tblExchangeRate AS Exch
ON Jobs.CurrencyID = Exch.CurrencyID
AND Year(Jobs.[BillDate]) = Year(Exch.[CurrencyDate])
AND Month(Jobs.[BillDate]) = Year(Exch.[CurrencyDate]);