将mysql值赋给变量内联

时间:2011-04-11 15:12:08

标签: mysql mysql-error-1054

为什么这不起作用我试图获得先前和当前值来计算百分比变化。我正确地得到了两个值,但现在我如何重用它们来进行数学运算

当我尝试以下命令时,我得到了 ERROR 1054(42S22):'字段列表'中的未知列'currentVal'

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

2 个答案:

答案 0 :(得分:2)

你不能在同一个SELECT中引用别名列,你必须把它放在一个子查询中:

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

答案 1 :(得分:1)

围绕您当前拥有的内容换行另一个查询并计算您的百分比:

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