difference - how to subtract two resultant values in mysql -


say have table tablea , query

select id,         if(cond1, value, 0) firstval,         if(cond2, value, 0) secondval,         firstval-secondval diff  tablea 

the above query gives unknown column firstval in field list error. know can calculate diff if(cond1, value, 0)-if(cond2, value, 0) diff don't want add condition again , without inner/sub queries.

edit: abstract idea follows

table structure

id   |    type   |  recorddate  | value =========================================  1               2015-12-17       9  2         b       2015-12-19       5  3               2016-01-13       31  4         b       2016-01-14       23  5               2016-01-31       44  6         b       2016-02-07       38 

and on...

query:

 select      type,      if(max(recorddate), value, 0) firstval,      if(secondmax(recorddate), value, 0) secndval,      firstval-secndval diff   table   month(recorddate)=1  group type rollup 

resultant table based on above query:

type  | firstval  |  secndval  |  diff ======================================       44           31          13  b      23           5           18 total   67           36          31            

add sub-query

select *, firstval-secondval diff           (select id, if(cond1, value, 0) firstval, if(cond2, value, 0) secondval         tablea      ) t 

Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

java - Digest auth with Spring Security using javaconfig -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -