2

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 ...;
OMG Ponies
  • 325,700
  • 82
  • 523
  • 502
user391986
  • 29,536
  • 39
  • 126
  • 205

2 Answers2

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;
manji
  • 47,442
  • 5
  • 96
  • 103
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
Joe Stefanelli
  • 132,803
  • 19
  • 237
  • 235