MySQL - 如何将子查询中的列别名用于另一个子查询?
Posted
技术标签:
【中文标题】MySQL - 如何将子查询中的列别名用于另一个子查询?【英文标题】:MySQL - How to use the columns alias from subqueries for another sub query? 【发布时间】:2020-11-10 04:30:32 【问题描述】: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;
错误代码:1054。“字段列表”中的“馆藏”列未知。
表定义为,name varchar,type of contract
varchar,balance int。
我知道错误出在哪里,我无法使用子查询中的列别名,但我不知道如何在另一种方法中执行查询。
【问题讨论】:
正确的解决方案 - 将您的查询转换为 CTE 或子查询。姑息疗法 - 使用用户定义的变量。 【参考方案1】:您可以使用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
【讨论】:
但在持有和借款时,我需要余额的总和,而不仅仅是余额。 @NithinGowda,你执行了查询吗? 抱歉过早发表评论。它工作正常。谢谢。 @NithinGowda,请不要忘记将其标记为已接受的答案 :)以上是关于MySQL - 如何将子查询中的列别名用于另一个子查询?的主要内容,如果未能解决你的问题,请参考以下文章
Python-Sqlalchemy-Postgres:如何将子查询结果存储在变量中并将其用于主查询