A
A
Artyom2020-02-13 12:30:29
MySQL
Artyom, 2020-02-13 12:30:29

How to sort records before grouping?

I need to:
1. Count the number of new messages
2. Group by sender
3. Display in descending order. From newer to older.

The problem is that it is not possible to sort in descending order before grouping. And after grouping, it no longer makes sense, because. in the grouping, the first value with the date is taken.

Tried to sort with a nested query something like this:

SELECT `r`.`room`, COUNT(`m`.`id`), `m`.`date` 
FROM (SELECT * FROM `messenger` ORDER BY `date` DESC) AS `m`
JOIN `rooms` AS `r` ON `m`.`id_room` = `r`.`id` 
GROUP BY (`m`.`id_room`)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Artyom, 2020-02-13
@RizyaRU

I solved the issue with the MAX () function, getting the correct, for me, date.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question