简体   繁体   中英

mysql desc doesnt work for me

it should make a list and at the top the highest percentage.. but it doesnt https://gyazo.com/ecde864ef09115b8b119eba8a39ecd68 here the picture when i run it

and here the code. What is wrong?

$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;";

You percent column is a string, so they are sorted lexicographically (eg, 8 is treated as larger than 26, since "8" comes after "2"). Instead, you could sort on the numeric part, before the concatination. This can be done with the current query, but it would be much more elegant to more the total punten to a subquery:

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

Use the underlying value. Converting a number to a string and then back to a number is awkward. So:

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;

I also moved the subquery to the FROM clause. This is often more efficient.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM