Answer the question
In order to leave comments, you need to log in
How to sort and then group a SQL selection first?
I need to find one last action of users, and I get the first one
SELECT
*
FROM
(
SELECT
act.*,
users.name,
users.lname,
users.ava_file
FROM
act
INNER JOIN users WHERE act.date > "1517427936" AND act.date < "1517428356" AND act.creator = users.id
ORDER BY
act.date
DESC
) a
GROUP BY
a.creator
SELECT
b.*,
users.name,
users.lname,
users.ava_file
FROM
(
SELECT
a.*
FROM
(
SELECT
act.*
FROM
act
WHERE
act.date > "1517427936" AND act.date < "1517428356"
ORDER BY
act.id
DESC
) a
GROUP BY
a.creator
) b
INNER JOIN users WHERE b.creator = users.id
Answer the question
In order to leave comments, you need to log in
sort in calculations up to F, this is just a way to display
the table draw
Something like that?
CREATE TEMPORARY TABLE `act_tmp`
SELECT
`act`.*
FROM
`act`
LEFT JOIN(
SELECT
`creator`,
MAX(`date`) AS `date`
FROM
`act`
WHERE
`act`.`date` > "1517427936" AND `act`.`date` < "1517428356"
GROUP BY
`creator`
) AS `act_b`
ON
`act`.`creator` = `act_b`.`creator` AND `act`.`date` = `act_b`.`date`
WHERE
`act_b`.`creator` IS NOT NULL
GROUP BY
`act`.`creator`;
SELECT
`act_tmp`.*,
`users`.`name`,
`users`.`lname`,
`users`.`ava_file`
FROM
`users`
LEFT JOIN `act_tmp` ON `users`.`id` = `act_tmp`.`creator`
WHERE
`act_tmp`.`creator` IS NOT NULL
GROUP BY
`users`.`id`
And what is the point of sorting, which will then be "recomputed" by the grouping?
By the way, many SQL dialects will not allow you to use fields in the output that do not participate in grouping without aggregation.
I mean
select
user_id,
act_date
from table
group by user_id
select
user_id,
min(act_date) -- или max|sum|avg и т.п.
from table
group by user_id
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question