2013-05-17 67 views
0

我有一張ECB匯率表,我想計算每年的平均匯率。TSQL - 計算完整年度貨幣匯率的AVG

讓我這個圖片說明:

image

正如你可以看到在這個例子在現有的年取AVG每種貨幣的AVGRate。 輸出應該只顯示每個貨幣的一個AVG,在這種情況下給我四行。

所以最終的輸出版本應該給我ECBDate(像「BRL-2013-01-02」),AVGRate和Year列。

當然這也應該適用於2014年等等。

請參閱我的Fiddle,瞭解到目前爲止所得到的結果。

謝謝你的幫助。

回答

2

嘗試這一個 -

查詢:

DECLARE @Original TABLE 
(
    [Date] DATE, 
    Currency VARCHAR(3), 
    Rate NUMERIC(9,4) 
) 

INSERT INTO @Original ([Date], Currency, Rate) 
VALUES 
    ('2013-01-02', 'BRL', 2.707), 
    ('2013-01-03', 'BRL', 2.6828), 
    ('2013-01-02', 'CNY', 8.1703), 
    ('2013-01-03', 'CNY', 8.4014), 
    ('2013-01-02', 'CZK', 25.218), 
    ('2013-01-03', 'CZK', 25.26), 
    ('2013-01-02', 'USD', 1.3262), 
    ('2013-01-03', 'USD', 1.3102) 

;WITH cte AS 
(
    SELECT 
      * 
     , [Year] = YEAR(o.[Date]) 
     , id = ROW_NUMBER() OVER (PARTITION BY YEAR(o.[Date]), Currency ORDER BY Currency) 
    FROM @Original o 
    WHERE o.[Date] BETWEEN '2013-01-01' AND '2014-01-01' 
) 
SELECT 
     ECB_Date = t.Currency + '-' + CAST(t.[Date] AS CHAR(10)) 
    , ECB_Rate = t.Rate 
    , t.[Year] 
    , t2.AVG_ECBRate 
FROM cte t 
LEFT JOIN (
    SELECT DISTINCT 
      o.Currency 
     , o.[Year] 
     , id = MAX(id) OVER (PARTITION BY o.[Year], o.Currency) 
     , AVG_ECBRate = AVG(CONVERT(NUMERIC(9,4), o.Rate)) OVER (PARTITION BY o.[Year], o.Currency) 
    FROM cte o 
) t2 ON t.Currency = t2.Currency AND t.[Year] = t2.[Year] AND t.id = t2.id 

輸出:

ECB_Date  ECB_Rate Year  AVG_ECBRate 
-------------- ---------- ----------- ----------- 
BRL-2013-01-02 2.7070  2013   
BRL-2013-01-03 2.6828  2013  2.694900 
CNY-2013-01-02 8.1703  2013   
CNY-2013-01-03 8.4014  2013  8.285850 
CZK-2013-01-02 25.2180 2013   
CZK-2013-01-03 25.2600 2013  25.239000 
USD-2013-01-02 1.3262  2013   
USD-2013-01-03 1.3102  2013  1.318200 
+1

你已經辦完了:-) – SvenB

+0

我很高興第一個(簡單)版本來幫你。說實話,很長一段時間,我不明白錯誤在哪裏。我可以向你建議我們免費的在線SQL格式化服務[Online SQL Format](http://www.sql-format.com/)。 – Devart