如何计算排序的两个别名的差异

时间:2016-07-29 18:29:16

标签: mysql reference alias

考虑以下代码:

SELECT SUM(w.valor),
SUM(CASE WHEN w.tipo = '+' THEN w.valor ELSE 0 END) AS total_credit,
SUM(CASE WHEN w.tipo = '-' THEN w.valor ELSE 0 END) AS total_debit,
w.clientUNIQUE,
c.client as cclient
FROM wallet AS w
LEFT JOIN clients AS c ON w.clientUNIQUE = c.clientUNIQUE
WHERE w.status='V'
GROUP BY w.clientUNIQUE
ORDER BY total_credit-total_debit

我尝试计算两个别名计算值的差异以进行排序,但我收到以下错误:

  

参考' total_credit'不支持(参考群组功能)

我做错了什么以及如何使用两个别名之间的差值来订购结果?

1 个答案:

答案 0 :(得分:3)

您无法在同一个选择表达式中按别名引用列,因此有2个选项...

重复order by(yuk)中的表达式:

ORDER BY
  SUM(CASE WHEN w.tipo = '+' THEN w.valor ELSE 0 END) AS total_credit -
  SUM(CASE WHEN w.tipo = '-' THEN w.valor ELSE 0 END) AS total_debit

大脑更容易维护(DRY),通过子查询订购:

select * from (
  <your query without the ORDER BY>
) q
ORDER BY total_credit - total_debit