如何按SELECT查询中两个SUM / COUNT的比例进行排序?

时间:2016-12-08 23:02:10

标签: mysql select sql-order-by

SELECT查询中

SELECT 
category_id, 
COUNT(*) AS Total, 
SUM(IF(year=2016,1,0) AS year2016, 
SUM(IF(year=2015,1,0) AS year2015
FROM articles
GROUP BY category_id

我如何ORDER BY year2016/year2015的比例?

1 个答案:

答案 0 :(得分:2)

SELECT语句移动到子查询中将允许您重新使用计算的SUM聚合。转换为DECIMAL将告诉MySQL不要使用整数除法并保持小数点右边的值。

SELECT category_id, Total, year2016, year2015
FROM
  (SELECT 
    category_id, 
    COUNT(*) AS Total, 
    SUM(IF(year=2016,1,0)) AS year2016, 
    SUM(IF(year=2015,1,0)) AS year2015
  FROM articles
  GROUP BY category_id) AS t
ORDER BY CAST(year2016 AS DECIMAL(14,4)) / CAST(year2015 AS DECIMAL(14,4))