我的MySQL知识 =初学者
Columns: MonthlyIncome and MonthlyDebt
Table: customer
所需输出:显示每月收入 - 月度差额的差异的MIN,MAX和AVE。 MonthlyIncome
- MonthlyDebt
= NetIncome
。
我的失败尝试:
失败的查询:
SELECT MonthlyIncome - MonthlyDebt AS NetIncome
FROM (
SELECT MIN(NetIncome) AS MinNet,
MAX(NetIncome) AS MaxNet,
AVE(NetIncome) AS AveNet
FROM customers
) AS subqueryalias
失败会产生 ERROR :
Error Code: 1054. Unknown column 'NetIncome' in 'field list'
答案 0 :(得分:1)
您在外部查询中定义了NetIncome
,但在内部查询中引用了它,这是一个不行。首先执行内部查询。我甚至不会使用别名,只需在所有聚合函数中使用表达式:
select min(MonthlyIncome - MonthlyDebt), max(MonthlyIncome - MonthlyDebt), avg(MonthlyIncome - MonthlyDebt)
from customers
答案 1 :(得分:0)
您需要将我们的SELECT
内外翻转为
SELECT
MIN(NetIncome) AS MinNet,
MAX(NetIncome) AS MaxNet,
AVE(NetIncome) AS AveNet
FROM ( SELECT MonthlyIncome - MonthlyDebt AS NetIncome
FROM customers ) AS subqueryalias
首先评估内部子查询SELECT MonthlyIncome - MonthlyDebt AS NetIncome FROM customers
并生成列NetIncome
,以便在外部(主要)select
中进一步使用。