0

我有一张欧洲央行汇率表,我想计算每年的平均汇率。

让我用这张图解释一下:

图片

如您所见,此示例中的 AVGrate 采用现有年份中每种货币的 AVG。然后输出应该只显示每种货币的一个 AVG,在这种情况下给我四行。

所以最终的输出版本应该给我 ECBDate(带有“BRL-2013-01-02”之类的记录)、AVGrate 和 Year 列。

当然,这也应该适用于 2014 年等等。

到目前为止,请参阅我的小提琴。

4

1 回答 1

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
于 2013-05-17T11:50:16.067 回答