assigning mysql value to variable inline

无人久伴 提交于 2019-12-11 08:44:57

问题


Why doesn't this work i'm trying to get the previous and current value to calculate percent change. I get both values correctly but now how can I reuse them to do the math operatio

When I try the below command I get ERROR 1054 (42S22): Unknown column 'currentVal' in 'field list'

            SELECT IFNULL(DValue,0) as currentVal, 
                      (SELECT IFNULL(DValue,0) 
                       FROM ...
                       WHERE...) as previousVal, 
                      (currentVal-previousVal)/previousVal
            FROM ...
            WHERE ...;

回答1:


Wrap another query around what you currently have and calculate your percentage there:

SELECT currentVal, previousVal, 
       (currentVal-previousVal)/previousVal AS percentChange
    FROM (SELECT IFNULL(DValue,0) as currentVal, 
                  (SELECT IFNULL(DValue,0) 
                       FROM ...
                       WHERE...) as previousVal
              FROM ...
              WHERE ...) t



回答2:


you can't reference an aliased column in the same SELECT, you have to put it in a subquery:

SELECT currentVal, previousVal, (currentVal-previousVal)/previousVal
FROM (
            SELECT    IFNULL(DValue,0) as currentVal, 
                      (SELECT IFNULL(DValue,0) 
                       FROM ...
                       WHERE...) as previousVal, 
            FROM ...
            WHERE ...) T;


来源:https://stackoverflow.com/questions/5623410/assigning-mysql-value-to-variable-inline

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