1

I am attempting to count number of records in a database by grouping them. This works fine, but when I try to order by, it orders the count by a different method than wanted. Example Result:

Question - Answer - Count

Q1 - A1 - 1

Q2 - A2 - 11

Q3 - A3 - 2

Result wanted: I want 11 after 2-9, not before. The query is simply:

SELECT Question, Answer, count(*) as `Count` GROUP BY Question, Answer ORDER BY Question, Answer

A further example of the sort is that the mysql sorts like, 1,11,118,12,2,3 where I am expecting the increasing value like 1,2,3,11,12,118

0

3 Answers 3

1

try this query

SELECT Question, Answer, count(*) as `Count`
FROM table
GROUP BY Question, Answer
ORDER BY count(*) ASC
Sign up to request clarification or add additional context in comments.

Comments

0

You have put in your query

ORDER BY Question, Answer

If you want 11 to come after 2, then surely you want

ORDER BY Count

Comments

0

The issue appears that I was trying to order by character value instead of integer value? I have to cast the answer as an integer and then it order properly. Here is the query that works:

SELECT Question, Answer, count(*) as `Count` GROUP BY Question, Answer ORDER BY Question, CAST( answer AS SIGNED INTEGER )

Found the answer here: Sorting varchar field numerically in MySQL

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.