annual change of values with subquery

拥有回忆 提交于 2019-12-25 03:50:39

问题


This query gives a 1093 error:

UPDATE values_table as outer_select 
    SET annual_change = sample_value - (
        SELECT sample_value FROM values_table 
        WHERE date_sampled = DATE_SUB(outer_select.date_sampled, INTERVAL 1 YEAR)
    );

I'm trying to set annual_change for every row equal to the current row's sample_value less last year's sample_value.

The data doesn't go back to the beginning time, so how can the lack of historical values also be handled?


回答1:


Try this

UPDATE values_table as a
join  values_table as b 
ON b.date_sampled = DATE_SUB(a.date_sampled, INTERVAL 1 YEAR)
set a.annual_change = a.sample_value - b.sample_value


来源:https://stackoverflow.com/questions/16257690/annual-change-of-values-with-subquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!