2017-07-04 66 views
0

我想對5月至6月之間的匯率變動進行區分,匯率以CZK(捷克克朗)借入的借款人總數與歐元相關。 例如:5月份,人們向我公司借入的金額爲27M捷克克朗(相當於1M歐元),由於匯率變動,6月份僅爲0.89M歐元。如何在貨幣匯率變動方面賺取差價

我來提供:

SELECT 
    SUM((
     SELECT Rate 
     FROM s96.CurrencyRates 
     WHERE (YEAR(Date)=2017) AND (MONTH(Date)=5) 
     ) * t.ApprovedLoanAmount) 
     - 
    SUM((
     SELECT Rate 
     FROM s96.CurrencyRates 
     WHERE (YEAR(Date)=2017) AND (MONTH(Date)=6) 
     ) * t.ApprovedLoanAmount) 
    AS currChange 
FROM(
     SELECT ApprovedLoanAmount 
     FROM dim.Contract con 
      JOIN dim.Calendar cal ON con.CreateDateID = cal.DateId 
     WHERE (cal.CalendarYear = 2017) AND (cal.MonthOfYear = 5) 
    ) t 

它返回:

不能對包含聚合或子查詢的表達式執行聚合功能。

任何幫助將被折扣。

+1

con.CreateDateID的列類型是什麼? (我懷疑「int」)你爲什麼期望能夠將它投射到一個日期? –

+0

是的,它是int。我希望能夠設置所需的日期。也許,我應該使用LEFT? –

+0

我猜你不想要那個CreatedDateID列,但一些「CreatedDate」值(或該表中的其他列)*是日期類型的*。或者你是否將日期編碼爲該值(int 20170704而不是日期2017-07-04)? –

回答

1

有幾個選項可以更改您的查詢。 您可以計算子查詢中的當前費率,並在1 = 1時使用左連接。 你也可以改變你的總和語句:

SELECT 
((
     SELECT SUM(Rate) 
     FROM s96.CurrencyRates 
     WHERE (YEAR(Date)=2017) AND (MONTH(Date)=5) 
     ) * t.ApprovedLoanAmount) 
    - 
    ((
     SELECT SUM(Rate) 
     FROM s96.CurrencyRates 
     WHERE (YEAR(Date)=2017) AND (MONTH(Date)=6) 
     ) * t.ApprovedLoanAmount) 
    AS currChange 
FROM(
     SELECT ApprovedLoanAmount 
     FROM dim.Contract con 
      JOIN dim.Calendar cal ON con.CreateDateID = cal.DateId 
     WHERE (cal.CalendarYear = 2017) AND (cal.MonthOfYear = 5) 
    ) t 
2

我不知道你的確切表怎麼看,所以覺得這更像是一個比片段複製/粘貼的解決方案:

SELECT 
    SUM(ApprovedLoanAmount) AS ApprovedLoanAmountCZK 
, SUM(ApprovedLoanAmountEUR_May) AS ApprovedLoanAmountEUR_May 
, SUM(ApprovedLoanAmountEUR_June) AS ApprovedLoanAmountEUR_June 
, SUM(ApprovedLoanAmountEUR_May) - SUM(ApprovedLoanAmountEUR_June) AS CurrChange 
FROM 
(
    SELECT ApprovedLoanAmount 
    , ApprovedLoanAmount * (SELECT Rate 
          FROM s96.CurrencyRates rM 
          WHERE rM.Date = cal.Date -- date of contract? 
          AND rM.Currency = 'EUR' -- if you have other currencies rates in same table 
    ) AS ApprovedLoanAmountEUR_May 
    , ApprovedLoanAmount * (SELECT Rate 
         FROM s96.CurrencyRates rJ 
         WHERE rJ.Date = '20170630' 
         AND rJ.Currency = 'EUR' 
    ) AS ApprovedLoanAmountEUR_June 
    FROM dim.Contract con 
    JOIN dim.Calendar cal ON con.CreateDateID = cal.DateId 
    WHERE (cal.CalendarYear = 2017) AND (cal.MonthOfYear = 5) 
) t 
  • 確保兩個子查詢率只返回一行每個
  • 更換cal.Date和rM.Currency與您的具體列
  • 替換cal.Date與「20170531」,如果你想在速度5月底替代合同日期
+0

CurrencyRates格式日期爲2016-12-30,但我不知道如何將日期與日期進行比較。例如。如果我寫「rj.Currency = 2017-06-30」,它會返回一個錯誤,因爲它無法與int進行比較。 此外,cal.Date是int ... –

+0

就像我說的,我不知道你的表的結構。你必須自己調整查詢。如果您遇到問題,請更新您的問題,以提供所有相關表格的結構和樣本數據(CurrencyRate,Contract,Calendar) –

相關問題