mysql desc对我不起作用

时间:2016-04-22 14:36:43

标签: mysql sql

它应该列出一个列表并且在顶部是最高百分比..但它不是 https://gyazo.com/ecde864ef09115b8b119eba8a39ecd68这是我运行时的图片

这里的代码。有什么问题?

$sql = "SELECT band, concat(round(sum(punten) *100 /
(SELECT sum(punten) FROM bands)) , \"%\") AS percent
FROM bands
WHERE punten>0
GROUP BY band 
ORDER BY percent DESC;";

2 个答案:

答案 0 :(得分:0)

百分比列是一个字符串,因此它们按字典顺序排序(例如,8被视为大于26,因为" 8"来自" 2")。相反,您可以在连接之前对数字部分进行排序。这可以使用当前查询来完成,但是对于子查询的总punten来说会更加优雅:

SELECT     band, CONCAT(ROUND(band_punten) * 100 / total_punten), '%') AS percent
FROM       (SELECT   band, SUM(punten) AS band_punten
            FROM     bands
            WHERE    punten > 0
            GROUP BY band) a
CROSS JOIN (SELECT SUM(punten) AS total_punten FROM bands) b
ORDER BY   band_punten DESC

答案 1 :(得分:0)

使用底层值。将数字转换为字符串然后返回到数字是很尴尬的。所以:

SELECT band,
       concat(round(sum(punten) * 100 / sump) , \"%\") AS percent
FROM bands CROSS JOIN
     (SELECT sum(punten) as sump FROM bands) x
WHERE punten > 0
GROUP BY band 
ORDER BY sum(punten) DESC;

我还将子查询移动到FROM子句。这通常更有效。