如何在具有别名的字段上进行ORDER BY

时间:2014-01-07 16:29:35

标签: mysql sql-order-by

我的查询如下

   SELECT
  final_avg_total.`Provider Name`,
  ROUND(SUM(final_avg_total.avg_total_payments), 2) AS avg_payments,
  ROUND(SUM(final_avg_total.avg_covered_charges), 2) AS avg_covered,
  (SUM(final_avg_total.avg_covered_charges) - SUM(final_avg_total.avg_total_payments)) / SUM(final_avg_total.avg_covered_charges) AS total_average,
  1 - (SUM(final_avg_total.avg_covered_charges) - SUM(final_avg_total.avg_total_payments))/SUM(final_avg_total.avg_covered_charges) AS total_percentage
FROM final_avg_total
GROUP BY final_avg_total.`Provider Id`
ORDER BY final_avg_total.`avg_payments`  DESC

我想在以下字段中使用别名avg_payments进行排序,但我收到此错误。

 Unknown column avg_payments in the order by clause

3 个答案:

答案 0 :(得分:2)

avg_payments不是表格中的字段。只需删除表别名:

ORDER BY avg_payments  DESC

MySQL了解order by语句中的列别名。

答案 1 :(得分:1)

avg_payments不是final_avg_total的属性,也许只是这样做:

ORDER BY avg_payments  DESC

答案 2 :(得分:1)

你可以尝试

order by 2.

1表示select语句中的序号位置,即final_avg_total。Provider Name然后2表示它是avg_payments。

注意:这只适用于mysql,如果我没记错的话。

希望这会有所帮助。