在SELECT中重用别名

时间:2011-08-16 00:52:48

标签: mysql sql database

我要做的是添加另一列计算(cr - dr)

看到你无法在SELECT子句中重复使用别名,你将如何进行计算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 ....

3 个答案:

答案 0 :(得分:9)

在SQL Server或Oracle中,我使用CTE,但由于您使用的是MySQL,因此您使用子查询:

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;

答案 1 :(得分:6)

编辑:不工作。看评论。 在这种情况下,没有使用user variable更快?

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

答案 2 :(得分:1)

您可以在" 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 ....