MySQL - 如何将子查询的列别名用于另一个子查询?

MySQL - How to use the columns alias from subqueries for another sub query?

select name, 
 (select sum(balance) from customers group by name having balance>0 and `type of contract`!="loan") as holdings, 
 (select sum(balance) from customers group by name having balance<0 or `type of contract`="loan") as borrowings, 
 (select case when holdings-borrowings>0 then "positive" else "negative" end from customers) as `positive/negative`, 
 holdings-borrowings as total 
 from customers 
 group by name 
 order by name;

Error Code: 1054. Unknown column 'holdings' in 'field list'.

table定义是,name varchar,type of contractvarchar,balance int。 我知道错误在哪里,我不能使用子查询中的列别名,但我不知道如何用另一种方法执行查询。

您可以使用 conditional aggregation

尝试以下操作

注意: 列别名不能用作投影列表中的参考,这就是您收到错误的原因

select name, 
sum(case when balance>0 and `type of contract`!="loan" then balance else 0 end) as holdings,
sum(case when balance<0 and `type of contract`="loan" then balance else 0 end) as borrowings,
case when (sum(case when balance>0 and `type of contract`!="loan" then balance else 0 end)-
sum(case when balance<0 and `type of contract`="loan" then balance else 0 end))>0 then 'positive' else 'negative' end as `positive/negative`,
sum(case when balance>0 and `type of contract`!="loan" then balance else 0 end)-
sum(case when balance<0 and `type of contract`="loan" then balance else 0 end) as total
from customers   
group by name 
order by name

或-

select name, holdings,borrowings,case when holdings-borrowings>0 then 'Postivie' else 'Negative' end as `positive/negative`,holdings-borrowings as total
from
(
select name, 
    sum(case when balance>0 and `type of contract`!="loan" then balance else 0 end) as holdings,
    sum(case when balance<0 and `type of contract`="loan" then balance else 0 end) as borrowings
    from customers   
    group by name
)A order by name