Reusing an alias in SELECT

What I'm trying to do is add another column that computes (cr-dr)

Seeing that you cannot reuse an alias inside a SELECT clause, how would you make a calculator total

    SELECT SUM(b.bet_win * cy.fx_rate )as dr, SUM(b.bet_loss * cy.fx_rate ) as cr, cr+dr as total
    FROM ....
    WHERE ....
+5
source share
3 answers

In SQL Server or Oracle, I would use CTE, but since you are using MySQL, you should use a subquery:

SELECT dr, cr, cr + dr as total 
FROM (
    SELECT 
         SUM(b.bet_win * cy.fx_rate ) as dr, 
         SUM(b.bet_loss * cy.fx_rate ) as cr
    FROM ....
    WHERE ....) t;
+9
source

EDIT: DOES NOT WORK. See Comments. Doesn't use a user variable faster in this case?

SELECT
  @dr:=SUM(b.bet_win * cy.fx_rate ),
  @cr:=SUM(b.bet_loss * cy.fx_rate ), 
  @cr+@dr as total
+6
source

"total".

SELECT 
    SUM(b.bet_win * cy.fx_rate) as dr, 
    SUM(b.bet_loss * cy.fx_rate) as cr, 
    SUM(b.bet_win * cy.fx_rate) + SUM(b.bet_loss * cy.fx_rate) as total
FROM ....
WHERE ....
+1
source

All Articles