Is possible to count alias result on mysql

。_饼干妹妹 提交于 2019-12-11 00:36:50

问题


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


来源:https://stackoverflow.com/questions/18466207/is-possible-to-count-alias-result-on-mysql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!