简体   繁体   中英

SQL: Count occurrences of column values within a time range and order by count

So I have a bunch of messages with a "room" column. What I want to do is find the top 5 rooms by number of messages. So if 1000 messages in the last 5 days are from room A and 500 are from room B, and so on I will be returned results in the form A, B, C, D, E.

I figured out how to find all of the "rooms" for the last 5 days

SELECT room 
FROM messages 
WHERE 
    timestamp < (SELECT UNIX_TIMESTAMP()*1000) 
    AND 
    timestamp > (SELECT UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 5 day))*1000);

But when I try to simply add ORDER BY count(room); to the end the entire list gets flattened into a single irrelevant result (the most recent message).

What am I missing?

As mentioned in the comment by M Khalid Junaid : group by the room column and then order by:

SELECT room,count(*)
FROM messages 
WHERE 
    timestamp < (SELECT UNIX_TIMESTAMP()*1000) 
    AND 
    timestamp > (SELECT UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 5 day))*1000)
group by room
order by 2 desc
limit 5;

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