MySQL更新查询与过去1年的平均值

时间:2016-02-21 12:00:35

标签: mysql sql-update

我正在尝试通过获取过去1年值的平均值来更新另一个表中的值。我在下面写的查询肯定是错误的,因为AsOfDate未包含在表b的查询中,但表明了我想要做的事情。提前谢谢。

update MT_1YR_AVG_EXGRATE a
join (select avg(ExchangeRate) as ExchangeRate, CurrencyId from Currency_Exchange_Rate_Data
        where BaseCurrencyId = "USD" group by CurrencyId) b
on b.CurrencyId = a.CurrencyId and b.AsOfDate <= a.AsOfDate and b.AsOfDate > date_sub(a.AsOfDate,interval 1 year)
set a.ExchangeRate = b.ExchangeRate
where a.ExchangeRate = null;

1 个答案:

答案 0 :(得分:0)

解决:

update MT_1YR_AVG_EXGRATE c join (
select b.CurrencyId, b.AsOfDate, avg(a.ExchangeRate) as ExchangeRate from Currency_Exchange_Rate_Data a, MT_1YR_AVG_EXGRATE b
    where a.BaseCurrencyId = "USD" and a.CurrencyId = b.CurrencyId and b.ExchangeRate is NULL
    and a.AsOfDate <= b.AsOfDate and a.AsOfDate > date_sub(b.AsOfDate,interval 1 year)
    group by b.CurrencyId, b.AsOfDate) d
on d.CurrencyId = c.CurrencyId and d.AsOfDate = c.AsOfDate
set c.ExchangeRate = cast(d.ExchangeRate as decimal(19,5))
where c.ExchangeRate is NULL;