平均mySQL中子查询的结果

时间:2014-04-21 18:50:06

标签: mysql sql

我正在建立一个查询医疗保险数据库,列出医生为各种程序收取的费用。

理想情况下,此查询将:

  • 返回每条记录,这意味着每位医生的每一个程序。 (我稍后会添加过滤WHERE子句)
  • 返回医生为每个程序收取的平均费用
  • 返回平均费用与每位医生收费之间的百分比差异
  • 返回每位医生所有这些百分比差异的平均值,产生元差异分数。

通过下面的查询,除了最后一个目标,我已经能够实现所有目标。

SELECT medicare.*, 
       peerAverage.average AS charge_average, 
       ( medicare.average_submitted_chrg_amt - peerAverage.average ) / 
       peerAverage.average * 100 AS difference_from_average,
       Avg( ( medicare.average_submitted_chrg_amt - peerAverage.average ) / 
       peerAverage.average * 100 ) as total_difference_from_average
FROM   medicare 
       JOIN (SELECT Avg(average_submitted_chrg_amt) AS average, 
                    procedure_code 
             FROM   medicare 
             GROUP  BY procedure_code) AS peerAverage 
         ON medicare.procedure_code = peerAverage.procedure_code 
ORDER  BY procedure_code ASC, 
          difference_from_average DESC 

当我添加最终SELECT条件(Avg( ( medicare.average_submitted_chrg_amt - peerAverage.average ) / peerAverage.average * 100 ) as total_difference_from_average)时,查询只返回一条记录。

删除该条件,查询返回正确的记录数。我做错了什么?

1 个答案:

答案 0 :(得分:0)

聚合函数可以提升聚合级别。在为平均函数指定分组条件之前,它将始终返回聚合在所有值上的一行,由表达式返回