E
E
ekaramazov2018-02-01 00:04:02
SQL
ekaramazov, 2018-02-01 00:04:02

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

and which of the queries is better to use? The second day I'm breaking my head over the problem.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Dimonchik, 2018-02-01
@dimonchik2013

sort in calculations up to F, this is just a way to display
the table draw

A
Alexander, 2018-02-01
@SAnhPa

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`

D
d-stream, 2018-02-01
@d-stream

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

will not work, but you need to aggregate act_date
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 question

Ask a Question

731 491 924 answers to any question