从别名列显示MIN,MAX和AVE

时间:2017-06-10 23:52:54

标签: mysql sql

我的MySQL知识 =初学者

Columns: MonthlyIncome and MonthlyDebt
Table: customer

所需输出:显示每月收入 - 月度差额的差异的MIN,MAX和AVE。 MonthlyIncome - MonthlyDebt = NetIncome

来自研究和实验的

我的失败尝试

  1. 获取两列之间的差异并将它们放在别名列中。
  2. 从别名列(NetIncome)中选择以显示MIN,MAX和AVE。
  3. 失败的查询:

    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'
    

2 个答案:

答案 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中进一步使用。