I created a wrapper query to calculate percentages like this…
SELECT reviewTotal, agreeCount, agreeTotal, (agreeCount/agreeTotal) * 100 AS agreePct
FROM(
SELECT and so on...
) AS wrapper
ORDER BY agreeCount DESC, created_on ASC
Everything is working fine, except for the following annoying data anomaly…
When the user chooses to display Comments sorted by “Agree” (Count), my query returns this result-set…
id agreeCount agreeTotal agreePct created_on
--- ----------- ----------- --------- -----------
16 5 5 100.0000 2014-07-01
33 2 4 50.0000 2014-07-05
19 1 4 25.0000 2014-07-15
2 0 2 0.0000 2014-08-01
7 0 0 NULL 2014-08-02
3 0 2 0.0000 2014-08-03
241 0 0 NULL 2014-08-04
The problem is that the order in which the zero agreeCounts are sorted is messing up my PHP formatting function, because when agreeTotal == 0 then it displays ‘–’, otherwise it displays ‘0’.
So I end up with…
Helpful: 0 (0%)
Helpful: --
Helpful: 0 (0%)
Helpful: --
Is there someway to tell MySQL this…
“Sort all Comments by “agreeCount” in descending order, AND if “agreeCount” == 0 then also sort by “agreeTotal” in descending order, otherwise don’t do an additional sort, AND after that go on ahead and sort by “created_on” in ascending order like the original query states.”
This is how I want the result-set to look…
id agreeCount agreeTotal agreePct created_on
--- ----------- ----------- --------- -----------
16 5 5 100.0000 2014-07-01
33 2 4 50.0000 2014-07-05
19 1 4 25.0000 2014-07-15
2 0 2 0.0000 2014-08-01
3 0 2 0.0000 2014-08-03
7 0 0 NULL 2014-08-02
241 0 0 NULL 2014-08-04
That way, my PHP will display Comments like this…
Helpful: 0 (0%)
Helpful: 0 (0%)
Helpful: --
Helpful: --
Displaying things this way will show the user Comments where people answered “Agree?” and some said “Yes” (i.e. agreeTotal = xx, agreeCount = xx), followed by people who answered “Agree?” and everyone said “No” (i.e. agreeTotal = xx, agreeCount = 0), followed by people who never even answered this question (i.e. agreeTotal = 0, agreeCount = 0, agreePct = NULL).
Hope that makes sense!
Sincerely,
Debbie