[英]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'.错误代码:1054。“字段列表”中的“持股”列未知。
The table definition is, name varchar, type of contract
varchar, balance int.表定义是,名称varchar, type of contract
varchar,余额int。 I know where the error is, I can't use the column alias from the subqueries but I don't know how to execute the query in another method.我知道错误在哪里,我不能使用子查询中的列别名,但我不知道如何在另一种方法中执行查询。
You can try the below using conditional aggregation
您可以使用conditional aggregation
尝试以下操作
Note: column alias can not be used as a reference in the projection list that's the reason you got the error注意:列别名不能用作投影列表中的参考,这就是您收到错误的原因
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
OR -或者 -
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.