如何使用我们在新列中的列中获得的变量

时间:2014-04-07 17:25:39

标签: mysql sql

以下是一个例子: 表"交易"列和#34;代码,借记卡,贷方"

我试图执行查询:

Select code, 
       Var1 = sum(debit) ,
       Var2 = sum(credit),  
       Balance_debit = Var1 - Var2, 
       Balance_credit = Var2 - Var1 
from transactions 
group by code

我知道我可以这样做:

Select code, 
       Var1 = sum(debit) ,
       Var2 = sum(credit),  
       Balance_debit =  sum(debit) -  sum(credit), 
       Balance_credit =   sum(credit) - sum(debit) 
from transactions 
group by code

但我后来有非常大的表达式,我想使用上一栏中的变量。

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

你可以这样做,

With CTE as
(
Select code, 
       sum(debit) as d,
       sum(credit) as c,  
       Balance_debit = Var1 - Var2, 
       Balance_credit = Var2 - Var1 
from transactions 
group by code
)
select code
    ,d as Debilt
    ,c as Credit
    ,d-c as Balance_debit 
   ,c-d as Balance_credit 
 from CTE