これを試してみてください -
クエリ:
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