Is possible to count alias result on mysql

2019-07-12 15:46发布

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

4条回答
走好不送
2楼-- · 2019-07-12 16:14
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
查看更多
霸刀☆藐视天下
3楼-- · 2019-07-12 16:27

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..
)
查看更多
一纸荒年 Trace。
4楼-- · 2019-07-12 16:36

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)
查看更多
一纸荒年 Trace。
5楼-- · 2019-07-12 16:38

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
查看更多
登录 后发表回答