Is possible to count alias result on mysql

2019-07-12 16:10发布

问题:

Actually my query is like this :

SELECT ABS(20-80) columnA , ABS(10-70) columnB ,
ABS(30-70) columnC , ABS(40-70) columnD , etc..

The pb is each ABS() is in fact some complex calculation , and i need to add a last columnTotal witch is the SUM of each ABS() , and i'd like to do that in one way without recalculate all . What i'd like to achieve is :

SELECT ABS(20-80) columnA , ABS(10-70) columnB ,
ABS(30-70) columnC , ABS(40-70) columnD , SUM(columnA+columnB+columnC+columnD) columnTotal 

. The result expected look like this :

columnA    columnB    columnC    columnD    columnTotal
  60         60          40         30          190

don't know if its possible

回答1:

Yes, in MySQL you can do it like this way:

SELECT 
  @a:=ABS(40-90) AS column1, 
  @b:=ABS(50-10) AS column2, 
  @c:=ABS(100-40) AS column3, 
  @a+@b+@c as columnTotal;
+---------+---------+---------+-------------+
| column1 | column2 | column3 | columnTotal |
+---------+---------+---------+-------------+
|      50 |      40 |      60 |         150 |
+---------+---------+---------+-------------+
1 row in set (0.00 sec)


回答2:

you can wrap it in one more layer like this:

select columnA, columnnB, columnnC, columnnD, (columnA+ columnnB+ columnnC+ columnnD) total
from 
(
SELECT ABS(20-80) columnA , ABS(10-70) columnB ,
ABS(30-70) columnC , ABS(40-70) columnD , etc..
)


回答3:

SELECT t.*, (columnA+columnB...) as total
FROM (
    SELECT ABS(20-80) columnA , ABS(10-70) columnB, ABS(30-70) columnC , ABS(40-70) columnD 
    ...
) as t


回答4:

Use a Derived Table:

SELECT
    columnA , columnB ,
    columnC , columnD ,
    SUM(columnA+columnB+columnC+columnD) columnTotal 
FROM
 (
   SELECT
       ABS(20-80) columnA , ABS(10-70) columnB ,
       ABS(30-70) columnC , ABS(40-70) columnD 
   FROM ...
 ) AS dt