nwolybug
nwolybug

Reputation: 472

mysql order by count - ordering by value

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

Upvotes: 1

Views: 320

Answers (3)

nwolybug
nwolybug

Reputation: 472

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

Upvotes: 0

Mattia Caputo
Mattia Caputo

Reputation: 969

try this query

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

Upvotes: 1

Matt
Matt

Reputation: 3353

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

Upvotes: 0

Related Questions