在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
的比例?
答案 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))