在SELECT表的其他地方使用子查询的别名

时间:2014-04-20 23:25:46

标签: mysql sql

我有一个医生为一个地区内的医疗程序收费的价格数据库。我想使用子查询将每位医生的价格(average_submitted_charge_amount)与平均价格进行比较。

SELECT *, 
    (SELECT Avg(average_submitted_chrg_amt) AS average 
    FROM    medicare 
    ) AS peerAverage, 
( ( average_submitted_chrg_amt - peerAverage.average ) / peeraverage.average 
) AS charge_deviation 
FROM medicare 

MySQL抛出错误:Unknown column 'peerAverage' in 'field list'。是否不允许在查询中的别名引用子查询?

2 个答案:

答案 0 :(得分:1)

将计算移至from子句:

SELECT m.*, peerAverage
      ((average_submitted_chrg_amt - peerAverage) / peeraverage
      ) AS charge_deviation 
FROM medicare m cross join
     (SELECT Avg(average_submitted_chrg_amt)  AS peerAverage 
      FROM medicare 
     ) const;

答案 1 :(得分:0)

有一个括号“)”更多:

尝试:

SELECT *, 
    (SELECT Avg(average_submitted_chrg_amt) AS average 
    FROM    medicare 
    ) AS peerAverage, 
( ( average_submitted_chrg_amt - peerAverage.average ) / peeraverage.average 
) AS charge_deviation 
FROM medicare

为了帮助您,请发布表格。