Suppose, I want to show a list of users ordering by the most number of messages they have sent.
I have 2 tables: Users
and Messages
I h
You can sort using an alias
:
SELECT user, COUNT(1) as cnt
FROM Messages
GROUP BY user
ORDER BY cnt DESC;
or position
:
SELECT user, COUNT(1) as cnt
FROM Messages
GROUP BY user
ORDER BY 2 DESC;
if you want to print the names join users table,
select user_name, count(*) from users inner join messages m on users.userid=m.messageid group by userid order by count(*) desc;
SELECT user, COUNT(*) FROM messages GROUP BY user ORDER BY count(*) DESC;