开发者

reusing alias in SELECT

开发者 https://www.devze.com 2023-03-28 13:05 出处:网络
What I am trying to do is add another column that calculates (cr - dr) Seeing as you cannot re-use an alias inside a SELECT clause, how would you go about calculatin total

What I am trying to do is add another column that calculates (cr - dr)

Seeing as you cannot re-use an alias inside a SELECT clause, how would you go about calculatin 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 ....


In SQL Server or Oracle, I'd use a CTE, but since you're using MySQL, you'd 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;


EDIT: DOES NOT WORK. See comments. Isn't using 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


You can repeat the calculations in the "total" column.

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 ....
0

精彩评论

暂无评论...
验证码 换一张
取 消